Example #1
0
        public User Create(User user, string password, bool isEmail)
        {
            // validation
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new AppException("Password is required");
            }

            if (isEmail)
            {
                if (_context.Users.Any(x => x.Email == user.Email))
                {
                    throw new AppException("Email \"" + user.Email + "\" is already taken");
                }
            }
            else
            {
                if (_context.Users.Any(x => x.Phone == user.Phone))
                {
                    throw new AppException("Phone \"" + user.Phone + "\" is already taken");
                }
            }

            byte[] passwordHash, passwordSalt;
            CreatePasswordHash(password, out passwordHash, out passwordSalt);

            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            _context.Users.Add(user);

            VerificationCode vcode = new VerificationCode
            {
                FieldType  = isEmail ? VerificationCode.EMAIL : VerificationCode.PHONE,
                FieldValue = isEmail ? user.Email : user.Phone
            };

            if (vcode.FieldType == VerificationCode.EMAIL)
            {
                vcode.ExpireDate = DateHelper.AddDay(1);
            }
            else if (vcode.FieldType == VerificationCode.PHONE)
            {
                vcode.ExpireDate = DateHelper.AddMinut(10);
            }
            if (_vcodeService.Send(vcode))
            {
                _context.VerificationCodes.Add(vcode);
            }

            _context.SaveChanges();

            return(user);
        }