public async Task <IActionResult> ForgetPassword(ForgetPassword model)
        {
            if (ModelState.IsValid)
            {
                CommonUser user = await _commonUserSvc.CheckUser(model.Email);

                if (user != null)
                {
                    string token       = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
                    var    callbackUrl = Url.Action("ResetPassword", "User", new { code = token });

                    using (var tx = CommonContext.Database.BeginTransaction())
                    {
                        user.Token    = token;
                        user.TokenUtc = DateTime.UtcNow;
                        CommonContext.Users.Update(user);

                        await CommonContext.SaveChangesAsync();

                        tx.Commit();
                    }

                    _logger.Error($"Sending Email email:{model.Email} callback:{callbackUrl}");
                    bool result = await _mailSvc.SendPasswordResetEmail(model.Email, callbackUrl);

                    _logger.Error($"Email Sent:");
                }
                ViewBag.SucessMessage = "Please check your email for a link to reset your password";
                return(View());
            }

            return(View(model));
        }
예제 #2
0
        public async Task <IActionResult> Create(PartitionViewModel model)
        {
            if (ModelState.IsValid)
            {
                var nameAlreadyExists = CommonContext.Partitions.Any(x => x.Name.ToLower() == model.Name.ToLower());
                if (nameAlreadyExists)
                {
                    // duplicate partition name
                    ModelState.AddModelError(string.Empty, "Name already exsits.");
                    return(View(model));
                }

                var partition = new Partition();
                partition.Name             = model.Name;
                partition.ConnectionString = Cryptography.Encrypt(model.ConnectionString);
                partition.CreateUserId     = User.GetLoggedInUserId().Value;
                partition.UpdateUserId     = partition.CreateUserId = User.GetLoggedInUserId().Value;


                //put dude in the database
                using (var tx = CommonContext.Database.BeginTransaction())
                {
                    CommonContext.Partitions.Add(partition);
                    await CommonContext.SaveChangesAsync();

                    tx.Commit();
                }
                return(RedirectToAction("Index"));
            }
            return(View(model));
        }
예제 #3
0
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Attach(Member).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MemberExists(Member.member_no))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
예제 #4
0
        public async Task <IActionResult> Edit(CityModel model)
        {
            if (ModelState.IsValid)
            {
                var cityExists = await CommonContext.Cities.Where(x => x.Name.ToLower() == model.Name.ToLower() && x.Id != model.Id).AnyAsync();

                if (cityExists)
                {
                    ModelState.AddModelError(nameof(model.Name), "This name already exists.");
                    return(View(model));
                }


                var city = await CommonContext.Cities.SingleAsync(m => m.Id == model.Id);

                city.County       = model.County;
                city.Latitude     = model.Latitude;
                city.Longitude    = model.Longitude;
                city.Name         = model.Name;
                city.State        = model.State;
                city.StateCode    = model.StateCode;
                city.TimeZone     = model.TimeZone;
                city.Type         = model.Type;
                city.UpdateUserId = User.GetLoggedInUserId().Value;

                CommonContext.Cities.Update(city);
                await CommonContext.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
예제 #5
0
        public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordModel model)
        {
            var response = new APIResponse <ResetPasswordModel>()
            {
                Success = true
            };

            try
            {
                if (ModelState.IsValid)
                {
                    CommonUser user = await _commonUserSvc.CheckUser(model.Email);

                    if (user != null)
                    {
                        string token       = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
                        var    callbackUrl = Url.Action("ResetPassword", "User", new { code = token });

                        using (var tx = CommonContext.Database.BeginTransaction())
                        {
                            user.Token    = token;
                            user.TokenUtc = DateTime.UtcNow;
                            CommonContext.Users.Update(user);

                            await CommonContext.SaveChangesAsync();

                            tx.Commit();
                        }

                        bool result = await _mailSvc.SendPasswordResetEmail(model.Email, callbackUrl);

                        response.Message = "Please check your email for a link to reset your password";
                    }
                    else
                    {
                        response.Message = "Please check your email for a link to reset your password";
                    }
                }
                else
                {
                    response.Success = false;
                    response.Errors.AddRange(ModelState.ToErrors());
                }

                return(Ok(response));
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
                return(Ok(response));
            }
        }
예제 #6
0
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.member.Add(Member);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
예제 #7
0
        /// <summary>
        /// create new violation type
        /// </summary>
        /// <param name="violationtype"></param>
        /// <param name="createdById"></param>
        /// <returns></returns>
        public async Task <ServiceResponse <CommonViolationType> > CreateViolationType(CommonViolationType violationtype, Guid createdById)
        {
            var result = new ServiceResponse <CommonViolationType>();

            try
            {
                using (var scope = _commonCtx.Database.BeginTransaction())
                {
                    violationtype.CreateUserId = createdById;
                    violationtype.UpdateUserId = createdById;

                    _commonCtx.CommonViolationTypes.Add(violationtype);

                    await _commonCtx.SaveChangesAsync();

                    //Adds this newly created violation to all the account ViolationTypes.
                    await CreateAccountViolationType(violationtype);

                    scope.Commit();
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error creating new Violation Type");

                throw ex;
            }

            return(result);
        }
        public async Task <IActionResult> Edit(AccountUserViewModelEdit model)
        {
            if (ModelState.IsValid)
            {
                var existingUser = await CommonContext.UserAccounts.Include(x => x.User)
                                   .Where(m => m.UserId == model.UserId && m.AccountId == CommonAccount.Id).SingleOrDefaultAsync();

                if (existingUser == null)
                {
                    throw new Exception($"User cannot be found. UserId:{model.UserId}");
                }

                if (User.GetLoggedInUserId().Value == model.UserId && !model.Permissions.HasFlag(AccountPermissions.AccountAdministrator))
                {
                    ModelState.AddModelError(string.Empty, "You cannot remove the Account Administrator permission");
                    model.FirstName = existingUser.User.FirstName;
                    model.LastName  = existingUser.User.LastName;
                    model.Email     = existingUser.User.Email;
                    return(View(model));
                }

                if (User.GetLoggedInUserId().Value == model.UserId && model.Disabled)
                {
                    ModelState.AddModelError(string.Empty, "You cannot disable your own account");
                    model.FirstName = existingUser.User.FirstName;
                    model.LastName  = existingUser.User.LastName;
                    model.Email     = existingUser.User.Email;
                    return(View(model));
                }

                existingUser.Permissions  = model.Permissions;
                existingUser.Disabled     = model.Disabled;
                existingUser.UpdateUserId = LoggedInUser.Id;
                existingUser.UpdateUtc    = DateTime.UtcNow;

                using (var tx = CommonContext.Database.BeginTransaction())
                {
                    CommonContext.UserAccounts.Update(existingUser);
                    await CommonContext.SaveChangesAsync();

                    tx.Commit();

                    var cacheKey = WebCacheKey.CommonUserAccount(CommonAccount.Number, existingUser.UserId.Value);
                    await _cache.RemoveAsync(cacheKey);
                }

                return(RedirectToAction("Users"));
            }

            return(View(model));
        }
예제 #9
0
        public async Task <IActionResult> Register([FromBody] UserRegisterModel model)
        {
            var response = new APIResponse <TokenResponseModel>();

            if (ModelState.IsValid)
            {
                var userAlreadyExists = await CommonContext.Users.AnyAsync(q => q.Email.ToLower() == model.Email.ToLower());

                if (userAlreadyExists)
                {
                    // This isn't a security risk because we've verified the email address already
                    response.Success = false;
                    response.Errors.Add(new Error {
                        Code = Common.Enums.ErrorCode.None, Message = "A user has already verified that email address."
                    });
                }
                else
                {
                    var user = new CommonUser();
                    user.Email = model.Email;
                    user.SetPassword(model.Password);
                    user.Permission = IsAdmin(model.Email);


                    //put dude in the database
                    using (var tx = CommonContext.Database.BeginTransaction())
                    {
                        CommonContext.Users.Add(user);
                        await CommonContext.SaveChangesAsync();

                        tx.Commit();
                    }

                    //Register user device
                    var device = await RegisterUserDevice(model, user);

                    //Return JWT Token
                    return(Ok(await CreateEncodedJwtToken(user)));
                }
            }
            else
            {
                response.Success = false;
                response.Errors.AddRange(ModelState.ToErrors());
            }
            return(Ok(response));
        }
예제 #10
0
        public async Task <IActionResult> OnPostAsync(long?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Member = await _context.member.FindAsync(id);

            if (Member != null)
            {
                _context.member.Remove(Member);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
예제 #11
0
        public async Task <IActionResult> Edit(EditUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userAlreadyExists = await CommonContext.Users.AsNoTracking().AnyAsync(q => q.Email.ToLower() == model.Email.ToLower() && q.Id != model.Id);

                if (userAlreadyExists)
                {
                    // This isn't a security risk because we've verified the email address already
                    ModelState.AddModelError(string.Empty, "A user has already verified that email address.");
                    PopulateDropDownEditUsers(model);
                    return(View(model));
                }

                var user = await CommonContext.Users.SingleAsync(m => m.Id == model.Id);

                user.Email      = model.Email;
                user.FirstName  = model.FirstName;
                user.LastName   = model.LastName;
                user.Permission = model.Permission;

                if (model.Password != null)
                {
                    user.SetPassword(model.Password);
                }

                CommonContext.Users.Update(user);
                await CommonContext.SaveChangesAsync();

                //Update user information in all other accounts
                await _commonAccountSvc.SaveAccountUser(user, User.GetLoggedInUserId().Value);

                if (User.GetLoggedInUserId().Value == user.Id)
                {
                    await PurgeLoggedInUser();
                }



                return(RedirectToAction("Index"));
            }

            PopulateDropDownEditUsers(model);
            return(View(model));
        }
예제 #12
0
        public async Task <bool> RegisterUserDevice(UserDeviceModel model, CommonUser user)
        {
            var deviceAlreadyExists = await CommonContext.CommonUserDevices.SingleOrDefaultAsync(m => m.DeviceToken == model.DeviceToken && m.UserId == user.Id);

            if (deviceAlreadyExists != null)
            {
                deviceAlreadyExists.IsLogin         = true;
                deviceAlreadyExists.UpdateUserId    = user.Id;
                deviceAlreadyExists.DevicePublicKey = model.DevicePublicKey;

                using (var tx = CommonContext.Database.BeginTransaction())
                {
                    CommonContext.CommonUserDevices.Update(deviceAlreadyExists);
                    await CommonContext.SaveChangesAsync();

                    tx.Commit();
                }
            }
            else
            {
                CommonUserDevice userDevice = new CommonUserDevice()
                {
                    DeviceName      = model.DeviceName,
                    DeviceToken     = model.DeviceToken,
                    DeviceType      = model.DeviceType,
                    DevicePublicKey = model.DevicePublicKey,
                    UserId          = user.Id,
                    IsLogin         = true,
                    CreateUserId    = user.Id
                };

                using (var tx = CommonContext.Database.BeginTransaction())
                {
                    CommonContext.CommonUserDevices.Add(userDevice);
                    await CommonContext.SaveChangesAsync();

                    tx.Commit();
                }
            }

            return(true);
        }
        public async Task <IActionResult> ChangePassword([FromBody] ChangePassword model, Guid Id)
        {
            var response = new APIResponse <ChangePassword>()
            {
                Success = true
            };

            if (ModelState.IsValid)
            {
                var user = await CommonContext.Users.SingleOrDefaultAsync(m => m.Id == Id);

                if (user != null)
                {
                    if (user.CheckPassword(model.OldPassword))
                    {
                        user.SetPassword(model.NewPassword);
                        CommonContext.Users.Update(user);
                        await CommonContext.SaveChangesAsync();

                        response.Message = "Password Changed Successfully.";
                    }
                    else
                    {
                        response.Success = false;
                        response.Errors.Add(new Error()
                        {
                            Code = 0, Message = "Incorrect Password."
                        });
                    }
                }
            }
            else
            {
                response.Success = false;
                response.Errors.AddRange(ModelState.ToErrors());
            }

            return(Ok(response));
        }
예제 #14
0
        public async Task <IActionResult> Create(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userAlreadyExists = await CommonContext.Users.AnyAsync(q => q.Email.ToLower() == model.Email.ToLower());

                if (userAlreadyExists)
                {
                    // This isn't a security risk because we've verified the email address already
                    ModelState.AddModelError(string.Empty, "This email address already exists.");
                    PopulateDropDownUsers(model);
                    return(View(model));
                }

                var user = new CommonUser();
                user.Email     = model.Email;
                user.FirstName = model.FirstName;
                user.LastName  = model.LastName;
                user.SetPassword(model.Password);
                user.Permission   = model.Permission;
                user.CreateUserId = User.GetLoggedInUserId().Value;
                user.UpdateUserId = user.CreateUserId = User.GetLoggedInUserId().Value;


                //put dude in the database
                using (var tx = CommonContext.Database.BeginTransaction())
                {
                    CommonContext.Users.Add(user);
                    await CommonContext.SaveChangesAsync();

                    tx.Commit();
                }
                return(RedirectToAction("Index"));
            }

            //, "users", new { Area = Area.Admin });
            PopulateDropDownUsers(model);
            return(View(model));
        }
예제 #15
0
        public async Task <IActionResult> Create(CityModel model)
        {
            if (ModelState.IsValid)
            {
                var cityExists = await CommonContext.Cities.Where(x => x.Name.ToLower() == model.Name.ToLower()).AnyAsync();

                if (cityExists)
                {
                    ModelState.AddModelError(nameof(model.Name), "This name already exists.");
                    return(View(model));
                }

                var city = new City()
                {
                    County       = model.County,
                    Latitude     = model.Latitude,
                    Longitude    = model.Longitude,
                    Name         = model.Name,
                    State        = model.State,
                    StateCode    = model.StateCode,
                    TimeZone     = model.TimeZone,
                    Type         = model.Type,
                    CreateUserId = User.GetLoggedInUserId().Value,
                    UpdateUserId = User.GetLoggedInUserId().Value,
                };

                using (var tx = CommonContext.Database.BeginTransaction())
                {
                    CommonContext.Cities.Add(city);
                    await CommonContext.SaveChangesAsync();

                    tx.Commit();
                }
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
        public async Task <IActionResult> AssociateUser([FromBody] AccountUserAssociationModel model)
        {
            var response = new APIResponse <CommonUserAccountModel>()
            {
                Success = true
            };

            var commonUser = await CommonContext.Users.SingleOrDefaultAsync(m => m.Id == model.UserId);

            if (commonUser == null)
            {
                response.Success = false;
                response.Message = "User could not be found";
            }
            else
            {
                var commonUserAccount = await CommonContext.UserAccounts.Where(m => m.UserId == model.UserId && m.AccountId == model.AccountId).SingleOrDefaultAsync();

                //If these is no association, create it.
                if (commonUserAccount == null)
                {
                    commonUserAccount = new CommonUserAccount {
                        AccountId = model.AccountId, UserId = model.UserId, CreateUserId = model.UserId, UpdateUserId = model.UserId
                    };

                    CommonContext.UserAccounts.Add(commonUserAccount);
                    await CommonContext.SaveChangesAsync();
                }

                await _commonAccountSvc.SaveAccountUser(commonUser, commonUser.CreateUserId);

                response.Data = Mapper.Map <CommonUserAccountModel>(commonUserAccount);
            }

            return(Ok(response));
        }
        public async Task <ActionResult> Register(UserRegisterModel model)
        {
            if (ModelState.IsValid)
            {
                var userAlreadyExists = await CommonContext.Users.AnyAsync(q => q.Email.ToLower() == model.Email.ToLower());

                if (userAlreadyExists)
                {
                    // This isn't a security risk because we've verified the email address already
                    ModelState.AddModelError(string.Empty, "A user has already verified that email address.");
                }
                else
                {
                    var user = new CommonUser();

                    user.Email = model.Email;
                    user.SetPassword(model.Password);
                    user.Permission = IsAdmin(model.Email);

                    //put dude in the database
                    using (var tx = CommonContext.Database.BeginTransaction())
                    {
                        CommonContext.Users.Add(user);
                        await CommonContext.SaveChangesAsync();

                        tx.Commit();

                        await SignInUser(user, false);

                        return(RedirectToAction("Index", "Accounts", new { Area = Area.Admin }));
                    }
                }
            }

            return(View(model));
        }
        public async Task <IActionResult> ResetPassword(ResetPassword model)
        {
            if (ModelState.IsValid)
            {
                Guid userid     = new Guid(model.Id);
                var  userDetail = (from a in CommonContext.Users where a.Id == userid select new { a }).SingleOrDefault();
                if (userDetail != null)
                {
                    userDetail.a.SetPassword(model.Password);
                    using (var tx = CommonContext.Database.BeginTransaction())
                    {
                        userDetail.a.Token = null;
                        CommonContext.Users.Update(userDetail.a);
                        await CommonContext.SaveChangesAsync();

                        tx.Commit();
                    }
                    await SignInUser(userDetail.a, false);

                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View(model));
        }
예제 #19
0
 public async Task <int> Create_banan(banan ba)
 {
     _context.banans.Add(ba);
     return(await _context.SaveChangesAsync());
 }
        /// <summary>
        /// Creates a new Account in the Common and Account partitions.
        /// Also creates a user in the Account Partition if one doesn't exist.
        /// </summary>
        /// <param name="commonAccount"></param>
        /// <param name="user"></param>
        /// <param name="createdById"></param>
        /// <returns></returns>
        public async Task <ServiceResponse <CommonAccount> > CreateAccount(CommonAccount commonAccount, Guid createdById, List <AccountViolationType> AccViolationType, long CitationCounter)
        {
            var result = new ServiceResponse <CommonAccount>();

            try
            {
                using (var scope = _commonCtx.Database.BeginTransaction())
                {
                    //Get the correct account database based on the partition that was chosen for the account.
                    var accountCtx = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(commonAccount.Partition.ConnectionString));

                    if (accountCtx == null)
                    {
                        _logger.Error($"Account context does not exists for partition: {Cryptography.Decrypt(commonAccount.Partition.ConnectionString)}");

                        throw new Exception("Account context does not exists");
                    }

                    //Generate a random account number
                    commonAccount.Number = await GetNextAccountNumberAsync();

                    commonAccount.CreateUserId = createdById;
                    commonAccount.UpdateUserId = createdById;

                    //Create empty account settings
                    commonAccount.Settings = new CommonAccountSettings {
                    };
                    commonAccount.Settings.CreateUserId = createdById;
                    commonAccount.Settings.UpdateUserId = createdById;

                    _commonCtx.CommonAccounts.Add(commonAccount);

                    await _commonCtx.SaveChangesAsync();


                    //Update the count on the partition to let us know how many account reside on one database.
                    commonAccount.Partition.Occupancy = commonAccount.Partition.Occupancy + 1;
                    _commonCtx.Partitions.Update(commonAccount.Partition);


                    //If a Owner is selected, create a user account assosication.
                    if (commonAccount.OwnerUserId != null)
                    {
                        CommonUserAccount userAccount = new CommonUserAccount();
                        userAccount.CreateUserId = createdById;
                        userAccount.AccountId    = commonAccount.Id;
                        userAccount.UpdateUserId = createdById;
                        userAccount.UserId       = commonAccount.OwnerUserId;
                        userAccount.Permissions  = (AccountPermissions)Enum.GetValues(typeof(AccountPermissions)).Cast <int>().Sum();

                        _commonCtx.UserAccounts.Add(userAccount);
                        await _commonCtx.SaveChangesAsync();

                        var commonUser = await _commonCtx.Users.SingleAsync(m => m.Id == commonAccount.OwnerUserId);

                        //Add any new users to acconts
                        await SaveAccountUser(commonUser, createdById);
                    }

                    //Add Account in account context
                    //The Ids for the Account in AccountContext and CommonAccount in CommonContext are going to be exactly the same.
                    accountCtx.Accounts.Add(new Account {
                        Id = commonAccount.Id, Name = commonAccount.Name, CreateUserId = createdById, UpdateUserId = createdById
                    });

                    await accountCtx.SaveChangesAsync();


                    foreach (var Type in AccViolationType)
                    {
                        if (Type.IsCheckedViolation == true)
                        {
                            CommonAccountViolationType AccountViolationType = new CommonAccountViolationType();
                            AccountViolationType.CreateUserId    = createdById;
                            AccountViolationType.AccountId       = commonAccount.Id;
                            AccountViolationType.UpdateUserId    = createdById;
                            AccountViolationType.ViolationTypeId = Type.TypeId;

                            _commonCtx.CommonAccountViolationTypes.Add(AccountViolationType);
                        }
                    }

                    await _commonCtx.SaveChangesAsync();

                    await _violationSvc.PopulateViolationsForAccount(commonAccount, createdById);

                    Counter count = new Counter()
                    {
                        AccountId    = commonAccount.Id,
                        Name         = "Citations",
                        NextValue    = CitationCounter,
                        CreateUserId = commonAccount.OwnerUserId.Value,
                        UpdateUserId = commonAccount.OwnerUserId.Value
                    };
                    accountCtx.Counters.Add(count);

                    await accountCtx.SaveChangesAsync();

                    scope.Commit();
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error creating new Account");


                throw ex;
            }

            return(result);
        }
        public async Task <ActionResult> CreatePassword(CreatePassword model)
        {
            if (ModelState.IsValid)
            {
                //Create new User and Account
                var user = new CommonUser();
                user.Email      = model.InvitedEmail;
                user.FirstName  = model.FirstName;
                user.LastName   = model.LastName;
                user.Permission = model.SystemPermission;
                user.SetPassword(model.Password);


                //Check Account
                var commonAccount = await CommonContext.CommonAccounts.Where(m => m.Id == model.AccountId).SingleOrDefaultAsync();

                var vendorDetail = await _accountCtx.Vendors.Where(x => x.Id == model.VendorId).SingleOrDefaultAsync();


                if (commonAccount == null)
                {
                    ViewBag.SucessMessage = "Account not found";
                    return(View(model));
                }

                CommonUserAccount userAccount = new CommonUserAccount();
                userAccount.CreateUserId = commonAccount.OwnerUserId.Value;
                userAccount.AccountId    = commonAccount.Id;
                userAccount.UpdateUserId = commonAccount.OwnerUserId.Value;
                userAccount.UserId       = user.Id;
                userAccount.Permissions  = (AccountPermissions)model.Permission;

                if (vendorDetail != null)
                {
                    user.Permission = SystemPermissions.Vendor;
                }

                using (var tx = CommonContext.Database.BeginTransaction())
                {
                    CommonContext.Users.Add(user);
                    await CommonContext.SaveChangesAsync();

                    CommonContext.UserAccounts.Add(userAccount);
                    await CommonContext.SaveChangesAsync();

                    tx.Commit();
                }

                //Create AccountUser
                var accountUser = new AccountUser
                {
                    Id        = userAccount.UserId.Value,
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    Email     = user.Email
                };

                _accountCtx.AccountUsers.Add(accountUser);

                if (vendorDetail != null)
                {
                    AccountUserVendor accountUserVendor = new AccountUserVendor();
                    accountUserVendor.VendorId      = vendorDetail.Id;
                    accountUserVendor.AccountUserId = accountUser.Id;

                    _accountCtx.AccountUserVendors.Add(accountUserVendor);
                }

                await _accountCtx.SaveChangesAsync();

                await SignInUser(user, false);

                return(RedirectToAction("Index", "Accounts"));
            }
            return(View(model));
        }
        public async Task <ActionResult> AcceptInvite(AcceptInvite model)
        {
            //Check to see if this user exists in Users
            var existingUser = await CommonContext.Users.Where(m => m.Email == model.InvitedEmail).AnyAsync();

            if (existingUser)
            {
                //Check to see if this user already belongs to the account
                //Users can belong to multiple accounts, we need to filter by accountID and InvitedEmail
                var existingAccountUser = await CommonContext.UserAccounts.Include(x => x.User).Where(m => m.User.Email == model.InvitedEmail && m.AccountId == model.AccountId).AnyAsync();

                if (!existingAccountUser)
                {
                    //Get exists User Detail
                    var user = CommonContext.Users.Where(m => m.Email == model.InvitedEmail).SingleOrDefault();

                    //Get Account detail using accountId
                    var commonAccount = await CommonContext.CommonAccounts.Where(m => m.Id == model.AccountId).SingleOrDefaultAsync();

                    var vendorDetail = await _accountCtx.Vendors.Where(x => x.Id == model.VendorId).SingleOrDefaultAsync();

                    if (commonAccount == null)
                    {
                        ViewBag.SucessMessage = "Account not found";
                        return(View(model));
                    }

                    CommonUserAccount userAccount = new CommonUserAccount();
                    userAccount.CreateUserId = commonAccount.OwnerUserId.Value;
                    userAccount.AccountId    = commonAccount.Id;
                    userAccount.UpdateUserId = commonAccount.OwnerUserId.Value;
                    userAccount.UserId       = user.Id;
                    userAccount.Permissions  = (AccountPermissions)model.Permission;

                    using (var tx = CommonContext.Database.BeginTransaction())
                    {
                        CommonContext.UserAccounts.Add(userAccount);
                        await CommonContext.SaveChangesAsync();

                        tx.Commit();
                    }

                    var accountUser = await _accountCtx.AccountUsers.Where(m => m.Id == user.Id).SingleOrDefaultAsync();

                    if (accountUser == null)
                    {
                        //Create AccountUser
                        accountUser = new AccountUser()
                        {
                            Id        = user.Id,
                            FirstName = user.FirstName,
                            LastName  = user.LastName,
                            Email     = user.Email,
                        };
                        _accountCtx.AccountUsers.Add(accountUser);
                        await _accountCtx.SaveChangesAsync();
                    }

                    if (vendorDetail != null)
                    {
                        AccountUserVendor accountUserVendor = new AccountUserVendor();
                        accountUserVendor.VendorId      = vendorDetail.Id;
                        accountUserVendor.AccountUserId = accountUser.Id;

                        user.Permission = SystemPermissions.Vendor;
                        CommonContext.SaveChanges();

                        using (var tx = _accountCtx.Database.BeginTransaction())
                        {
                            _accountCtx.AccountUserVendors.Add(accountUserVendor);
                            await _accountCtx.SaveChangesAsync();

                            tx.Commit();
                        }
                    }

                    return(RedirectToAction("Index", "Accounts"));
                }
                else
                {
                    ViewBag.SucessMessage = " Already Account user.";
                    return(View(model));
                }
            }
            else
            {
                CreatePassword pwdmodel = new Models.User.CreatePassword();
                pwdmodel.AccountId    = model.AccountId;
                pwdmodel.AccountName  = model.AccountName;
                pwdmodel.InvitedEmail = model.InvitedEmail;
                string[] name = model.Name.Split(' ');
                pwdmodel.FirstName        = name[0];
                pwdmodel.LastName         = name[1];
                pwdmodel.Permission       = model.Permission;
                pwdmodel.VendorId         = model.VendorId;
                pwdmodel.SystemPermission = model.SystemPermission;
                return(View("CreatePassword", pwdmodel));
            }
        }
        public async Task <IActionResult> Edit(UserModel model)
        {
            ModelState.Remove("ProfileImageKey");
            if (ModelState.IsValid)
            {
                var userAlreadyExists = await CommonContext.Users.AsNoTracking().AnyAsync(q => q.Email.ToLower() == model.Email.ToLower() && q.Id != model.Id);

                if (userAlreadyExists)
                {
                    // This isn't a security risk because we've verified the email address already
                    ModelState.AddModelError(string.Empty, "A user has already verified that email address.");

                    return(View(model));
                }

                //Get current file extension
                if (model.files != null)
                {
                    List <string> Types = _appSettings.ImageTypes.Split(',').ToList();
                    string        ext   = System.IO.Path.GetExtension(model.files.FileName).ToLower();
                    if (Types.Contains(ext))
                    {
                        if (model.files.Length > _appSettings.ImageSize)
                        {
                            //Convert bytes into MB
                            var size = (_appSettings.ImageSize / 1024f) / 1024f;
                            ModelState.AddModelError(string.Empty, $"File size  not be greater than {size} MB.");
                            return(View(model));
                        }

                        if (model.ProfileImageKey != null)
                        {
                            //Delete the file from AWS Bucket and Database
                            var cityAppFile = await _fileService.DeleteFile(model.ProfileImageKey, _appSettings.AWSAccessKeyID, _appSettings.AWSSecretKey, _appSettings.AmazonS3Bucket);
                        }


                        Guid fileGuid = Guid.NewGuid();
                        using (var fileStream = model.files.OpenReadStream())
                            using (var ms = new MemoryStream())
                            {
                                fileStream.CopyTo(ms);
                                //convert image into Bytes
                                var fileByte1s = ms.ToArray();
                                //Common/User/(UserId)/Profile/(new Guid()).(ext)
                                var fileNameInFolder = $"common/User/{User.GetLoggedInUserId().Value}/profile/{fileGuid + ext}";

                                //Upload the file on Amazon S3 Bucket
                                var result = await _fileService.UploadFile(fileByte1s, fileNameInFolder, _appSettings.AWSAccessKeyID, _appSettings.AWSSecretKey, true);

                                model.ProfileImageKey = fileNameInFolder;
                            }
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, $"Invalid File Formate {model.files.FileName}.");
                        return(View(model));
                    }
                }



                var user = await CommonContext.Users.SingleAsync(m => m.Id == model.Id);

                user.Email           = model.Email;
                user.FirstName       = model.FirstName;
                user.LastName        = model.LastName;
                user.ProfileImageKey = model.ProfileImageKey;

                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    if (!string.IsNullOrWhiteSpace(model.OldPassword))
                    {
                        if (user.CheckPassword(model.OldPassword))
                        {
                            user.SetPassword(model.Password);
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Invalid old password.");
                            return(View(model));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Invalid old password.");
                        return(View(model));
                    }
                }

                CommonContext.Users.Update(user);
                await CommonContext.SaveChangesAsync();

                //Update user information in all other accounts
                await _commonAccountSvc.SaveAccountUser(user, User.GetLoggedInUserId().Value);

                //Update user information in cache
                await PurgeLoggedInUser();
            }

            if (!string.IsNullOrWhiteSpace(model.ProfileImageKey))
            {
                //Read the file from AWS Bucket
                var cityAppFile = await _fileService.ReadFile(model.ProfileImageKey, _appSettings.AWSAccessKeyID, _appSettings.AWSSecretKey, _appSettings.AmazonS3Bucket);

                if (cityAppFile.FileBytes != null)
                {
                    cityAppFile.FileStream.Position = 0;
                    // Convert byte[] to Base64 String
                    model.ImageName = Convert.ToBase64String(cityAppFile.FileBytes);
                }
            }

            ViewBag.SucessMessage = "Your profile has been updated";
            return(View(model));
        }
        public async Task <IActionResult> UpdateProfile([FromBody] UserModel model)
        {
            var response = new APIResponse <UserModel>();

            if (ModelState.IsValid)
            {
                // if user is trying to update someone else profile.
                if (User.GetJWTLoggedInUserId() != model.Id)
                {
                    response.Success = false;
                    response.Errors.Add(new Error {
                        Code = 0, Message = "Invalid ID"
                    });
                    return(Ok(response));
                }



                var userAlreadyExists = await CommonContext.Users.AsNoTracking().AnyAsync(q => q.Email.ToLower() == model.Email.ToLower() && q.Id != model.Id);

                if (userAlreadyExists)
                {
                    // This isn't a security risk because we've verified the email address already
                    response.Success = false;
                    response.Errors.Add(new Error {
                        Code = 0, Message = "A user has already verified that email address."
                    });
                    return(Ok(response));
                }
                var user = await CommonContext.Users.SingleAsync(m => m.Id == model.Id);

                user.Email           = model.Email;
                user.FirstName       = model.FirstName;
                user.LastName        = model.LastName;
                user.PhoneNumber     = model.PhoneNumber;
                user.ProfileImageKey = model.profileImageKey;


                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    user.SetPassword(model.Password);
                }

                CommonContext.Users.Update(user);
                await CommonContext.SaveChangesAsync();

                //Update user information in all other accounts
                await _commonAccountSvc.SaveAccountUser(user, model.Id);

                //purge the user cache
                var cacheKey = WebCacheKey.LoggedInUser(model.Id);
                await _cache.RemoveAsync(cacheKey);

                response.Message = "Your profile has been updated";
            }
            else
            {
                response.Success = false;
                response.Errors.AddRange(ModelState.ToErrors());
            }

            return(Ok(response));
        }