Beispiel #1
0
        private bool IsCardTester(PaymentForm pf, string from)
        {
            if (!Util.IsHosted || !pf.CreditCard.HasValue())
            {
                return(false);
            }

            var hash = Pbkdf2Hasher.HashString(pf.CreditCard);

            CurrentDatabase.InsertIpLog(Request.UserHostAddress, hash);

            if (pf.IsProblemUser())
            {
                return(LogRogueUser("Problem User", from));
            }

            var iscardtester = ConfigurationManager.AppSettings["IsCardTester"];

            if (!iscardtester.HasValue())
            {
                return(false);
            }
            var result = CurrentDatabase.Connection.ExecuteScalar <string>(iscardtester, new { ip = Request.UserHostAddress });

            if (result.Equal("OK"))
            {
                return(false);
            }

            return(LogRogueUser(result, from));
        }
Beispiel #2
0
        public ValidateResult Validate(string credentialTypeCode, string identifier, string secret)
        {
            CredentialType credentialType = _context.CredentialType.FirstOrDefault(ct => ct.Code.ToLower() == credentialTypeCode.ToLower());

            if (credentialType == null)
            {
                return(new ValidateResult(success: false, error: ValidateResultError.CredentialTypeNotFound));
            }

            Credential credential = _context.Credential.FirstOrDefault(c => c.CredentialTypeId == credentialType.Id && c.Identifier == identifier);

            if (credential == null)
            {
                return(new ValidateResult(success: false, error: ValidateResultError.CredentialNotFound));
            }

            if (!string.IsNullOrEmpty(secret))
            {
                byte[] salt = Convert.FromBase64String(credential.Extra);
                string hash = Pbkdf2Hasher.ComputeHash(secret, salt);

                if (credential.Secret != hash)
                {
                    return(new ValidateResult(success: false, error: ValidateResultError.SecretNotValid));
                }
            }

            return(new ValidateResult(user: _context.Users.Find(credential.UserId), success: true));
        }
Beispiel #3
0
        public SignUpResult SignUp(UserModel user, string credentialTypeCode, string identifier, string secret)
        {
            _context.Users.Add(user);
            _context.SaveChanges();

            CredentialType credentialType = _context.CredentialType.FirstOrDefault(ct => ct.Code.ToLower() == credentialTypeCode.ToLower());

            if (credentialType == null)
            {
                return(new SignUpResult(success: false, error: SignUpResultError.CredentialTypeNotFound));
            }

            Credential credential = new Credential();

            credential.UserId           = user.ID;
            credential.CredentialTypeId = credentialType.Id;
            credential.Identifier       = identifier;

            if (!string.IsNullOrEmpty(secret))
            {
                byte[] salt = Pbkdf2Hasher.GenerateRandomSalt();
                string hash = Pbkdf2Hasher.ComputeHash(secret, salt);

                credential.Secret = hash;
                credential.Extra  = Convert.ToBase64String(salt);
            }

            _context.Credential.Add(credential);
            _context.SaveChanges();
            return(new SignUpResult(user: user, success: true));
        }
Beispiel #4
0
        private bool IsCardTester(PaymentForm pf, string from)
        {
            if (!Util.IsHosted || !pf.CreditCard.HasValue())
            {
                return(false);
            }
            var hash = Pbkdf2Hasher.HashString(pf.CreditCard);
            var db   = DbUtil.Db;

            db.InsertIpLog(HttpContextFactory.Current.Request.UserHostAddress, hash);

            if (pf.IsProblemUser())
            {
                return(OnlineRegController.LogRogueUser("Problem User", from));
            }
            var iscardtester = ConfigurationManager.AppSettings["IsCardTester"];

            if (!iscardtester.HasValue())
            {
                return(false);
            }
            var result = db.Connection.ExecuteScalar <string>(iscardtester, new { ip = HttpContextFactory.Current.Request.UserHostAddress });

            if (result.Equal("OK"))
            {
                return(false);
            }
            return(OnlineRegController.LogRogueUser(result, from));
        }
Beispiel #5
0
        public ChangeSecretResult ChangeSecret(string credentialTypeCode, string identifier, string secret)
        {
            CredentialType credentialType = _context.CredentialType.FirstOrDefault(ct => ct.Code.ToLower() == credentialTypeCode.ToLower());

            if (credentialType == null)
            {
                return(new ChangeSecretResult(success: false, error: ChangeSecretResultError.CredentialTypeNotFound));
            }

            Credential credential = _context.Credential.FirstOrDefault(c => c.CredentialTypeId == credentialType.Id && c.Identifier == identifier);

            if (credential == null)
            {
                return(new ChangeSecretResult(success: false, error: ChangeSecretResultError.CredentialNotFound));
            }

            byte[] salt = Pbkdf2Hasher.GenerateRandomSalt();
            string hash = Pbkdf2Hasher.ComputeHash(secret, salt);

            credential.Secret = hash;
            credential.Extra  = Convert.ToBase64String(salt);
            _context.Credential.Update(credential);
            _context.SaveChanges();
            return(new ChangeSecretResult(success: true));
        }
        public Credential Map(CredentialFilter filter, Credential credential, CreateOrEditViewModel createOrEdit)
        {
            if (credential.Id == 0)
            {
                credential.UserId = (int)filter.User.Id;
            }

            credential.CredentialTypeId = createOrEdit.CredentialTypeId;
            credential.Identifier       = createOrEdit.Identifier;

            if (!string.IsNullOrEmpty(createOrEdit.Secret))
            {
                if (createOrEdit.ApplyPbkdf2HashingToSecret)
                {
                    byte[] salt = Pbkdf2Hasher.GenerateRandomSalt();
                    string hash = Pbkdf2Hasher.ComputeHash(createOrEdit.Secret, salt);

                    credential.Secret = hash;
                    credential.Extra  = Convert.ToBase64String(salt);
                }

                else
                {
                    credential.Secret = createOrEdit.Secret;
                }
            }

            return(credential);
        }
Beispiel #7
0
        /// <summary>
        /// Enable: app__NoAccountLocalhost
        /// </summary>
        /// <param name="context"></param>
        public async Task Invoke(HttpContext context)
        {
            var isHostLocal = IsLocalhost.IsHostLocalHost(context.Connection.LocalIpAddress, context.Connection.RemoteIpAddress);
            var isApiCall   = context.Request.Path.HasValue && (context.Request.Path.Value.StartsWith("/api") ||
                                                                context.Request.Path.Value.StartsWith("/realtime"));

            var isFromLogoutCall = context.Request.QueryString.HasValue &&
                                   context.Request.QueryString.Value.Contains("fromLogout");

            if (isHostLocal && !context.User.Identity.IsAuthenticated && !isApiCall && !isFromLogoutCall)
            {
                var userManager = (IUserManager)context.RequestServices.GetService(typeof(IUserManager));

                var user = userManager.GetUser("email", Identifier);
                if (user == null)
                {
                    var newPassword = Convert.ToBase64String(
                        Pbkdf2Hasher.GenerateRandomSalt());
                    await userManager.SignUpAsync(string.Empty,
                                                  "email", Identifier, newPassword + newPassword);

                    user = userManager.GetUser("email", Identifier);
                }

                await userManager.SignIn(context, user, true);
            }
            await _next.Invoke(context);
        }
Beispiel #8
0
        public ChangeSecretResult ChangeSecret(string credentialTypeCode, string identifier, string secret)
        {
            var credentialType = _dbContext.CredentialTypes.FirstOrDefault(
                ct => ct.Code.ToLower().Equals(credentialTypeCode.ToLower()));

            if (credentialType == null)
            {
                return(new ChangeSecretResult(success: false, error: ChangeSecretResultError.CredentialTypeNotFound));
            }

            Credential credential = _dbContext.Credentials.TagWith("ChangeSecret").FirstOrDefault(
                c => c.CredentialTypeId == credentialType.Id && c.Identifier == identifier);

            if (credential == null)
            {
                return(new ChangeSecretResult(success: false, error: ChangeSecretResultError.CredentialNotFound));
            }

            var salt = Pbkdf2Hasher.GenerateRandomSalt();
            var hash = Pbkdf2Hasher.ComputeHash(secret, salt);

            credential.Secret = hash;
            credential.Extra  = Convert.ToBase64String(salt);
            _dbContext.Credentials.Update(credential);
            _dbContext.SaveChanges();

            if (IsCacheEnabled())
            {
                _cache.Set(CredentialCacheKey(credentialType, identifier),
                           credential, new TimeSpan(99, 0, 0));
            }

            return(new ChangeSecretResult(success: true));
        }
Beispiel #9
0
 public static void Initialize(TestContext testContext)
 {
     ApplicationUserValidator = new ApplicationUserValidator();
     FollowerValidator        = new FollowerValidator();
     CredentialValidator      = new CredentialValidator();
     CredentialTypeValidator  = new CredentialTypeValidator();
     RoleValidator            = new RoleValidator();
     UserRoleValidator        = new UserRoleValidator();
     RolePermissionValidator  = new RolePermissionValidator();
     PermissionValidator      = new PermissionValidator();
     Hasher        = new Pbkdf2Hasher();
     SaltGenerator = new RandomSaltGenerator();
 }
Beispiel #10
0
        public IActionResult ChangePassword(ChangeSecretDto model)
        {
            var currentUser = _partnerManager.GetPartnerById(this.HttpContext.User.Identity.Name);

            if (currentUser.Status.Id > 2)
            {
                return(Unauthorized(new ApiResponse(-3100, "Sorry, your account is not in correct state")));
            }
            if (currentUser.LockTime > DateTime.Now)
            {
                return(Unauthorized(new ApiResponse(-3101, $"Sorry, your account is suspended for {Utility.HowMuchLeftTime(currentUser.LockTime)}")));
            }
            if (!System.Text.RegularExpressions.Regex.IsMatch(model.newSecret.ToString(), "^[0-9]{4,6}$"))
            {
                return(BadRequest(new ApiResponse(-3102, $"Sorry, new secret was invalid")));
            }

            byte[] salt = Convert.FromBase64String(currentUser.Extra);
            string hash = Pbkdf2Hasher.ComputeHash(model.oldSecret.ToString(), salt);

            if (currentUser.Pwd != hash)
            {
                return(BadRequest(new ApiResponse(-3103, "Sorry, incorrect credentials")));
            }

            byte[] newSalt = Pbkdf2Hasher.GenerateRandomSalt();
            string newHash = Pbkdf2Hasher.ComputeHash(model.newSecret.ToString(), newSalt);

            var changeSecret = new ChangeSecretHistory();

            changeSecret.CreatedBy.Id        = currentUser.Id;
            changeSecret.CreatedBy.Account   = currentUser.Account;
            changeSecret.AccessChannel.Id    = "api";
            changeSecret.OldSalt             = currentUser.Extra;
            changeSecret.OldHash             = currentUser.Pwd;
            changeSecret.NewSalt             = Convert.ToBase64String(newSalt);
            changeSecret.NewHash             = newHash;
            changeSecret.ChangeType.Id       = "change";
            changeSecret.NotifyBy.Id         = "none";
            changeSecret.PartAppUser.Id      = currentUser.Id;
            changeSecret.PartAppUser.Account = currentUser.Account;
            var result = new ChangeSecretHistoryRepo(_db, _partnerManager, null).Create(changeSecret);

            //var result = _partnerManager.ChangePwd(currentUser.Account, currentUser.Id, model.newSecret.ToString(), false);
            if (!result.Success)
            {
                return(BadRequest(new ApiResponse(-3104, $"Sorry, change secrect was failed, please try later")));
            }

            return(Ok(new ApiResponse(0, $"Changed successfully")));
        }
 public static void Initialize(TestContext testContext)
 {
     MemeValidator            = new MemeValidator();
     ApplicationUserValidator = new ApplicationUserValidator();
     FollowerValidator        = new FollowerValidator();
     CredentialValidator      = new CredentialValidator();
     CredentialTypeValidator  = new CredentialTypeValidator();
     RoleValidator            = new RoleValidator();
     UserRoleValidator        = new UserRoleValidator();
     RolePermissionValidator  = new RolePermissionValidator();
     PermissionValidator      = new PermissionValidator();
     MemeFetcherService       = new LocalMemeFetcherService();
     SharedMemeValidator      = new SharedMemeValidator();
     CommentValidator         = new CommentValidator();
     Hasher        = new Pbkdf2Hasher();
     SaltGenerator = new RandomSaltGenerator();
 }
Beispiel #12
0
        /// <summary>
        /// Is the username and password combination correct
        /// </summary>
        /// <param name="credentialTypeCode">default: email</param>
        /// <param name="identifier">email</param>
        /// <param name="secret">password</param>
        /// <returns>status</returns>
        public async Task <ValidateResult> ValidateAsync(string credentialTypeCode,
                                                         string identifier, string secret)
        {
            var credentialType = CachedCredentialType(credentialTypeCode);

            if (credentialType == null)
            {
                return(new ValidateResult(success: false, error: ValidateResultError.CredentialTypeNotFound));
            }

            var credential = CachedCredential(credentialType, identifier);

            if (credential == null)
            {
                return(new ValidateResult(success: false, error: ValidateResultError.CredentialNotFound));
            }

            // No Password
            if (string.IsNullOrWhiteSpace(secret))
            {
                return(new ValidateResult(success: false, error: ValidateResultError.SecretNotValid));
            }

            var userData = (await AllUsersAsync()).FirstOrDefault(p => p.Id == credential.UserId);

            if (userData == null)
            {
                return(new ValidateResult(success: false, error: ValidateResultError.UserNotFound));
            }

            if (userData.LockoutEnabled && userData.LockoutEnd >= DateTime.UtcNow)
            {
                return(new ValidateResult(success: false, error: ValidateResultError.Lockout));
            }

            // To compare the secret
            byte[] salt           = Convert.FromBase64String(credential.Extra);
            string hashedPassword = Pbkdf2Hasher.ComputeHash(secret, salt);

            if (credential.Secret == hashedPassword)
            {
                return(await ResetAndSuccess(userData.AccessFailedCount, credential.UserId, userData));
            }

            return(await SetLockIfFailedCountIsToHigh(credential.UserId));
        }
        public Credential Map(CreateOrEditViewModel createOrEdit)
        {
            Credential credential = new Credential();

            if (createOrEdit.Id != null)
            {
                credential = this.RequestHandler.Storage.GetRepository <ICredentialRepository>().WithKey((int)createOrEdit.Id);
            }

            else
            {
                credential.UserId = createOrEdit.UserId;
            }

            credential.CredentialTypeId = createOrEdit.CredentialTypeId;
            credential.Identifier       = createOrEdit.Identifier;

            if (!string.IsNullOrEmpty(createOrEdit.Secret))
            {
                if (createOrEdit.ApplyPbkdf2HashingToSecret)
                {
                    byte[] salt = Pbkdf2Hasher.GenerateRandomSalt();
                    string hash = Pbkdf2Hasher.ComputeHash(createOrEdit.Secret, salt);

                    credential.Secret = hash;
                    credential.Extra  = Convert.ToBase64String(salt);
                }

                else
                {
                    credential.Secret = createOrEdit.Secret;
                }
            }

            return(credential);
        }
Beispiel #14
0
        public ActionResult <UserDto> Login(LoginDto loginDto)
        {
            var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
            var partnerResult   = this._partnerManager.Validate(loginDto.UserId);

            if (!partnerResult.Success)
            {
                var response = Unauthorized(new ApiResponse(401));
                _apiDbLog.Create(new ApiLogFile {
                    Data  = JsonSerializer.Serialize(response), Action = "login", Ip = remoteIpAddress.ToString(),
                    Level = 0, User = loginDto.UserId
                });
                return(response);
            }

            if (new ApiIPBlacklistRepo(_db).isBlacklisted(remoteIpAddress.ToString()))
            {
                var response = Unauthorized(new ApiResponse(401));
                _apiDbLog.Create(new ApiLogFile {
                    Data = $" blacklist ip {JsonSerializer.Serialize(response)}", Action = "login", Ip = remoteIpAddress.ToString(), Level = 0, User = loginDto.UserId
                });
                return(Unauthorized(new ApiResponse(401)));
            }

            if (partnerResult.Partner.IPAddress != remoteIpAddress.ToString())
            {
                new ApiIPBlacklistRepo(_db).Create(new ApiIPBlacklist {
                    IPAddress = remoteIpAddress.ToString()
                });
                return(Unauthorized(new ApiResponse(401)));
            }

            if (partnerResult.Partner.Status.Id > 2)
            {
                return(Unauthorized(new ApiResponse(401, "Sorry, your account is not in correct state")));
            }

            if (partnerResult.Partner.LockTime > DateTime.Now)
            {
                return(Unauthorized(new ApiResponse(401, $"Sorry, your account is suspended for {Utility.HowMuchLeftTime(partnerResult.Partner.LockTime)}")));
            }

            byte[] salt = Convert.FromBase64String(partnerResult.Partner.Extra);
            string hash = Pbkdf2Hasher.ComputeHash(loginDto.Password, salt);

            if (partnerResult.Partner.Pwd != hash)
            {
                bool lockAccount = partnerResult.Partner.WrongPwdAttempts >= 2;
                _partnerManager.IncreaseWrongPwdAttempts(partnerResult.Partner.Id, lockAccount);
                return(BadRequest(new ApiResponse(400, "Sorry, incorrect credentials")));
            }

            _partnerManager.PreSuccessLogin(partnerResult.Partner.Id);

            var user = new AppUser
            {
                Account = partnerResult.Partner.Account,
                Id      = partnerResult.Partner.Id,
                Name    = partnerResult.Partner.Name
            };

            return(new UserDto
            {
                Id = user.Id,
                Token = _tokenService.CreateToken(user),
                Account = user.Account
            });
        }
Beispiel #15
0
        /// <summary>
        /// Add a new user, including Roles and UserRoles
        /// </summary>
        /// <param name="name">Nice Name, default string.Emthy</param>
        /// <param name="credentialTypeCode">default is: Email</param>
        /// <param name="identifier">an email address, e.g. [email protected]</param>
        /// <param name="secret">Password</param>
        /// <returns>result object</returns>
        public async Task <SignUpResult> SignUpAsync(string name,
                                                     string credentialTypeCode, string identifier, string secret)
        {
            var credentialType = await AddDefaultCredentialType(credentialTypeCode);

            var roles = AddDefaultRoles();

            AddDefaultPermissions();
            AddDefaultRolePermissions();

            if (string.IsNullOrEmpty(identifier) || string.IsNullOrEmpty(secret))
            {
                return(new SignUpResult(success: false, error: SignUpResultError.NullString));
            }

            // The email is stored in the Credentials database
            var user = Exist(identifier);

            if (user == null)
            {
                // Check if user not already exist
                var createdDate = DateTime.UtcNow;
                user = new User
                {
                    Name    = name,
                    Created = createdDate
                };

                await _dbContext.Users.AddAsync(user);

                await _dbContext.SaveChangesAsync();
                await AddUserToCache(user);

                // to get the Id
                user = await _dbContext.Users.FirstOrDefaultAsync(p => p.Created == createdDate);

                if (user == null)
                {
                    throw new AggregateException("user should not be null");
                }
            }

            // Add a user role based on a user id
            AddToRole(user, roles.FirstOrDefault(p => p.Code == _appSettings.AccountRegisterDefaultRole.ToString()));

            if (credentialType == null)
            {
                return(new SignUpResult(success: false, error: SignUpResultError.CredentialTypeNotFound));
            }

            var credential = await _dbContext.Credentials.FirstOrDefaultAsync(p => p.Identifier == identifier);

            if (credential != null)
            {
                return(new SignUpResult(user: user, success: true));
            }

            // Check if credential not already exist
            credential = new Credential
            {
                UserId           = user.Id,
                CredentialTypeId = credentialType.Id,
                Identifier       = identifier
            };
            byte[] salt = Pbkdf2Hasher.GenerateRandomSalt();
            string hash = Pbkdf2Hasher.ComputeHash(secret, salt);

            credential.Secret = hash;
            credential.Extra  = Convert.ToBase64String(salt);
            await _dbContext.Credentials.AddAsync(credential);

            await _dbContext.SaveChangesAsync();

            return(new SignUpResult(user: user, success: true));
        }