Exemplo n.º 1
0
        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));
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
0
        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));
        }