public async Task <IActionResult> RegistorStoreV2([FromForm] RegistorStoreDTO model) { string messager = string.Empty; if (ModelState.IsValid) { // init store entity Store store = new Store { Id = Guid.NewGuid().ToString(), CategoryStoreId = model.CatStoreId, lat = model.lat, lon = model.lon, ProviderId = model.ProviderId, StatusStore = (int)TypeStatusStore.Open, StoreAddress = model.StoreAddress, StoreName = model.StoreName, }; // init user of store var hashPass = Helpers.SercurityHelper.GenerateSaltedHash(model.Password); User user = new User { Id = Guid.NewGuid().ToString(), Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, UserName = model.Email, HashPassword = hashPass.Hash, SaltPassword = hashPass.Salt, StoreId = store.Id, IsActived = (int)TypeVerified.Verified }; store.CreateByUserId = user.Id; store.Users.Add(user); // save store to database try { await _context.Stores.AddAsync(store); await _context.SaveChangesAsync(); messager = $"Khởi tạo cửa hàng {store.StoreName} thành công, vui lòng check email và đăng nhập để quản trị."; } catch (Exception ex) { _logger.Log(LogLevel.Warning, $"Log when RegistorStore {ex.Message}"); #if DEBUG throw new ApiException(ex); #else throw new ApiException($"Có lỗi xảy ra khi thêm mới store {store.StoreName}"); #endif } } _logger.Log(LogLevel.Information, messager); return(Ok(new { data = messager })); }
public async Task <IActionResult> UpdateSettings([FromBody] SettingDTO model, [FromHeader] string AuthenticationId, [FromHeader] string UserAgent, string settingType = "employee") { _logger.LogInformation("POST environment/{@settingType}", settingType); if (string.IsNullOrEmpty(AuthenticationId) || string.IsNullOrEmpty(UserAgent)) { throw new ApiException("Bạn không có quyền truy cập.", (int)HttpStatusCode.Unauthorized); } if (ModelState.IsValid) { model.SettingKey = model.SettingKey.Trim(); int typeSetting = settingType == "employee" ? (int)TypeSetting.EMPLPLOYEE : (int)TypeSetting.CUSTOMER; var settingExist = _context.Settings.FirstOrDefault(s => s.SettingKey.ToLower().Equals(model.SettingKey.Trim().ToLower()) && s.SettingType == typeSetting && s.CreatedBy.Equals(AuthenticationId)); // if settingKey exist if (settingExist != null) { // update _context.Entry(settingExist).State = Microsoft.EntityFrameworkCore.EntityState.Modified; settingExist.LastUpdated = DateTime.UtcNow; settingExist.LastUpdatedBy = AuthenticationId; settingExist.SettingValueVarchar = model.SettingValue; settingExist.SettingDesc = model.SettingDesc; } else { // other Create Setting setting = new Setting(); setting.CreatedBy = AuthenticationId; setting.LastUpdatedBy = AuthenticationId; setting.SettingType = typeSetting; setting.SettingKey = model.SettingKey; setting.SettingValueVarchar = model.SettingValue; setting.SettingDesc = model.SettingDesc; _context.Settings.Add(setting); } // save to database try { await _context.SaveChangesAsync(); } catch (System.Exception ex) { _logger.Log(LogLevel.Warning, "Có lỗi xảy ra khi update Settings", ex.Message); #if DEBUG throw new ApiException(ex); #else throw new ApiException("Có lỗi xảy ra khi update database"); #endif } } return(Ok(1)); }
public async Task <IActionResult> ImportData(string fileJSON) { // read jSON file string FileJSONPath = Path.Combine(_env.WebRootPath, fileJSON); // check file exist if (!System.IO.File.Exists(FileJSONPath)) { throw new ApiException("File path not exist", (int)HttpStatusCode.BadRequest); } // read File var JSON = System.IO.File.ReadAllText(FileJSONPath); IDictionary <string, ProviderDTO> jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject <IDictionary <string, ProviderDTO> >(JSON); List <Provider> providers = new List <Provider>(); // convert dictionary to object foreach (var item in jsonObj) { Provider provider = new Provider { Id = item.Key, Name = item.Value.Name, Code = item.Value.Code, ParentId = item.Value.ParentId, NameWithType = item.Value.NameWithType, Path = item.Value.Path, PathWithType = item.Value.PathWithType, Slug = item.Value.Slug, Type = item.Value.Type }; providers.Add(provider); } await _context.Providers.AddRangeAsync(providers); // save to db try { await _context.SaveChangesAsync(); } catch (System.Exception ex) { throw new ApiException(ex); } return(Ok(1)); }
public async Task <UserLogined> SignInAndSignUpCustomerAsync(CustomerLoginDTO model) { // GET roleCustomerUser var roleCustomerUser = await _context.Roles.FirstOrDefaultAsync(role => role.RoleName.Equals(RoleTypeHelper.RoleCustomerUser)); User userCreate = new User(); // CheckUserExist var userExist = await _context.Users .Include(u => u.UserToRoles) .ThenInclude(x => x.Role) .Where(u => u.UserToRoles.Any(x => x.RoleId == roleCustomerUser.Id)) .FirstOrDefaultAsync(u => u.Email.ToLower().Equals(model.Email.ToLower()) && u.UseExternalSignIns.Count > 0 && u.UserDevices.Count > 0); // case login lần sau: if (userExist != null) { // if exist then update user // update To UserDevices // update To UserExternalSignIns userCreate = userExist; _context.Entry(userCreate).State = EntityState.Modified; userCreate.LastLogin = DateTime.UtcNow; // check appId & currentUserId Exist if (!_context.UserDevices.Any(uc => uc.CurrentUserId == userCreate.Id && uc.CodeDevice == model.AppId)) { // Add to UserDevices var userDevice = new UserDevice { Id = Guid.NewGuid().ToString(), IsVerified = (int)TypeVerified.Verified, VerifiedCode = (int)(DateTime.Now.Ticks >> 23), CodeDevice = model.AppId, CurrentUserId = userCreate.Id, LastLogin = DateTime.UtcNow, TimeCode = 20 }; userCreate.UserDevices.Add(userDevice); } else { // Update to UserDevices var userDevice = _context.UserDevices.FirstOrDefault(uc => uc.CurrentUserId == userExist.Id && uc.CodeDevice == model.AppId); if (userDevice != null) { _context.Entry(userDevice).State = EntityState.Modified; userDevice.LastLogin = DateTime.UtcNow; // save tp db await _context.SaveChangesAsync(); } } // check exist UseExternalSignIns if (!_context.ExternalSignIns.Any(ue => ue.UserId == userCreate.Id && ue.TypeLogin == model.TypeLogin)) { var newUSERExternalSignIn = new ExternalSignIn { Id = Guid.NewGuid().ToString(), IsVerified = (int)TypeVerified.Verified, LastLogin = DateTime.UtcNow, TimeLifeToken = 3600, TokenLogin = model.TokenLogin, TypeLogin = model.TypeLogin, UserId = userExist.Id }; userCreate.UseExternalSignIns.Add(newUSERExternalSignIn); } else { // update To UserExternalSignIns var userExternalSignIn = _context.ExternalSignIns.FirstOrDefault(ue => ue.UserId == userExist.Id && ue.TypeLogin == model.TypeLogin); if (userExternalSignIn != null) { _context.Entry(userExternalSignIn).State = EntityState.Modified; userExternalSignIn.LastLogin = DateTime.UtcNow; // save tp db await _context.SaveChangesAsync(); } } // save to db await _context.SaveChangesAsync(); } else { // if not exist then create user userCreate.Id = Guid.NewGuid().ToString(); userCreate.FirstName = model.FirstName; userCreate.LastLogin = DateTime.UtcNow; userCreate.LastName = model.LastName; userCreate.Email = model.Email; userCreate.UserName = model.Email; userCreate.PhoneNumber = model.PhoneNumber; var userDevice = new UserDevice { Id = Guid.NewGuid().ToString(), CodeDevice = model.AppId, CurrentUserId = userCreate.Id, IsVerified = (int)TypeVerified.Verified, LastLogin = DateTime.UtcNow, TimeCode = 20, VerifiedCode = (int)(DateTime.Now.Ticks >> 23) }; // Save to UserDevices userCreate.UserDevices.Add(userDevice); var externalSign = new ExternalSignIn { Id = Guid.NewGuid().ToString(), IsVerified = (int)TypeVerified.Verified, LastLogin = DateTime.UtcNow, TimeLifeToken = 3600, TokenLogin = model.TokenLogin, TypeLogin = model.TypeLogin, UserId = userCreate.Id }; // Save to ExternalSignIns userCreate.UseExternalSignIns.Add(externalSign); // Save to UserToRole var userToRole = new UserToRole(); userToRole.Role = roleCustomerUser; userToRole.User = userCreate; roleCustomerUser.UserToRoles.Add(userToRole); _context.Users.Add(userCreate); // Save All To Database await _context.SaveChangesAsync(); } // create token string currentUserId = Guid.NewGuid().ToString(); var userLogined = CreateToken(userCreate, currentUserId); // save to login await SaveToUserLoginAsync(userCreate, userLogined, currentUserId); // save to login // return return(userLogined); }
public async Task <IActionResult> RegistrationUser([FromBody] RegistrationUserDTO model, string storeId) { _logger.Log(LogLevel.Information, "call registration/{@storeId}", storeId); await CheckIsSignoutedAsync(); string messager = string.Empty; if (ModelState.IsValid) { // check store exist and open Store store = await _context.Stores.FindAsync(storeId); if (store == null) { messager = "Không tìm thấy cửa hàng hoặc cửa hàng đã đóng."; _logger.Log(LogLevel.Information, messager); throw new ApiException(messager, (int)HttpStatusCode.BadRequest); } // get role Role role = await _context.Roles.FindAsync(storeId); if (role == null) { messager = "Không tìm thấy role."; _logger.Log(LogLevel.Information, messager); throw new ApiException(messager, (int)HttpStatusCode.BadRequest); } // init user var hashPass = Helpers.SercurityHelper.GenerateSaltedHash(model.Password); User user = new User { Id = Guid.NewGuid().ToString(), Age = model.Age, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, UserName = model.Username, StoreId = store.Id, Gender = model.Gender, IsActived = (int)TypeVerified.Verified, HashPassword = hashPass.Hash, SaltPassword = hashPass.Salt }; // Add user to Role UserToRole userToRole = new UserToRole(); userToRole.Role = role; userToRole.User = user; role.UserToRoles.Add(userToRole); // save user create to database try { _context.Roles.Add(role); _context.Users.Add(user); await _context.SaveChangesAsync(); messager = $"Đã khởi tạo nhân viên {role.Desc}: {user.FirstName} {user.LastName} cho cửa hàng của bạn."; } catch (Exception ex) { _logger.Log(LogLevel.Warning, $"Log when RegistrationUser {ex.Message}"); #if !DEBUG throw new ApiException($"Có lỗi xảy ra khi đăng ký {user.FirstName}", (int)HttpStatusCode.BadRequest); #else throw new ApiException(ex, (int)HttpStatusCode.BadRequest); #endif } } _logger.Log(LogLevel.Information, messager); return(Ok(new { data = messager })); }
public async Task <IActionResult> UpdateUserProfile([FromBody] UserProfileUpdateDTO model) { await CheckIsSignoutedAsync(); if (ModelState.IsValid) { // check user exist var user = await _context.Users.FindAsync(this.CurrentUserId); if (user == null) { throw new ApiException("User not found", (int)HttpStatusCode.BadRequest); } // check password if (!_authRepository.VerifyPasswordHash(model.CurrentPassword, user.HashPassword, user.SaltPassword)) { throw new ApiException("Wrong password.", (int)HttpStatusCode.BadRequest); } // update user _context.Entry(user).State = EntityState.Modified; user.FirstName = model.FirstName ?? "Nhân viên"; user.LastName = model.LastName ?? "ABC"; user.Gender = model.Gender ?? 1; user.PhoneNumber = model.PhoneNumber ?? string.Empty; user.UpdatedAt = DateTime.UtcNow; //// Update Birth day //if (model.YearOfBirth != 0 && model.MonthOfBirth != 0 && model.DayOfBirth != 0) //{ // user.BirthDay = new DateTime(model.YearOfBirth, model.MonthOfBirth, model.DayOfBirth); //} // Update Birth day if (model.YearOfBirth.HasValue && model.MonthOfBirth.HasValue && model.DayOfBirth.HasValue) { user.BirthDay = new DateTime(model.YearOfBirth.Value, model.MonthOfBirth.Value, model.DayOfBirth.Value); } if (!string.IsNullOrEmpty(model.NewPassword) && model.NewPassword != "string") { var hashPass = Helpers.SercurityHelper.GenerateSaltedHash(model.NewPassword.Trim()); user.HashPassword = hashPass.Hash; user.SaltPassword = hashPass.Salt; } // add User Detail if (user.UserDetail != null) { // update user.UserDetail.ProvideId = model.ProviderId ?? string.Empty; user.UserDetail.Address1 = model.Address1 ?? string.Empty; user.UserDetail.Address2 = model.Address2 ?? string.Empty; user.UserDetail.Address3 = model.Address3 ?? string.Empty; user.UserDetail.GAvartar = model.GAvartar ?? string.Empty; } else { UserDetail newUserDetail = new UserDetail(); newUserDetail.ProvideId = model.ProviderId ?? string.Empty; newUserDetail.Address1 = model.Address1 ?? string.Empty; newUserDetail.Address2 = model.Address2 ?? string.Empty; newUserDetail.Address3 = model.Address3 ?? string.Empty; newUserDetail.GAvartar = model.GAvartar ?? string.Empty; user.UserDetail = newUserDetail; } // save to database try { await _context.SaveChangesAsync(); } catch (System.Exception ex) { { _logger.Log(LogLevel.Warning, "Có lỗi xảy ra khi update user profile", ex.Message); #if DEBUG throw new ApiException(ex); #else throw new ApiException("Có lỗi xảy ra khi update database"); #endif } } } return(Ok(1)); }