public UserAccountModel getInfoUser(UserAccountModel model) { UserAccountDa dataAccess = new UserAccountDa(); UserAccountModel user = dataAccess.getInfoUser(model); return(user); }
public IHttpActionResult EditAccount([FromBody] UserAccountModel account) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var user = _mapper.Map <UserAccountModel, UserDTO>(account); user.Id = new Guid(User.Identity.GetUserId()); var result = _accountService.EditUser(user); if (!result.Succeeded) { return(Conflict()); } return(Ok()); } catch (Exception) { return(Conflict()); } }
public ActionResult EditUserAccount(string id) { using (var proxy = new UserServiceClient()) { var user = proxy.GetUserByKey(new Guid(id)); var model = UserAccountModel.CreateFromDto(user); var roles = proxy.GetRoles(); if (roles == null) { roles = new List <RoleDto>().ToArray(); } roles.ToList().Insert(0, new RoleDto() { Id = Guid.Empty.ToString(), Name = "(未指定)", Description = "(未指定)" }); if (model.Role != null) { ViewData["roles"] = new SelectList(roles, "Id", "Name", model.Role.Id); } else { ViewData["roles"] = new SelectList(roles, "Id", "Name", Guid.Empty.ToString()); } return(View(model)); } }
public async Task <int> CreateAccount(UserAccountModel model) { try { if (model.Username.Length <= 50 && model.EmailAddress.Length <= 50) { var storedProcedure = "dbo.UserAccount_Create"; DynamicParameters p = new DynamicParameters(); p.Add("Username", model.Username); p.Add("Password", model.Password); p.Add("Salt", model.Salt); p.Add("EmailAddress", model.EmailAddress); p.Add("AccountType", model.AccountType); p.Add("AccountStatus", model.AccountStatus); p.Add("CreationDate", model.CreationDate); p.Add("UpdationDate", model.UpdationDate); p.Add("Id", DbType.Int32, direction: ParameterDirection.Output); await _dataGateway.Execute(storedProcedure, p, _connectionString.SqlConnectionString); return(p.Get <int>("Id")); } else { return(0); } } catch (SqlCustomException e) { throw new SqlCustomException(e.Message, e.InnerException); } }
public async Task CreateAccount_ExecutionTimeLessThan400Milliseconds(int expectedId, string expectedUsername, string expectedPassword, string expectedSalt, string expectedEmailAddress, string expectedAccountType, string expectedAccountStatus, string expectedCreationDate, string expectedUpdationDate, long expectedMaxExecutionTime) { //Arrange UserAccountModel userAccountModel = new UserAccountModel(); userAccountModel.Id = expectedId; userAccountModel.Username = expectedUsername; userAccountModel.Password = expectedPassword; userAccountModel.Salt = expectedSalt; userAccountModel.EmailAddress = expectedEmailAddress; userAccountModel.AccountType = expectedAccountType; userAccountModel.AccountStatus = expectedAccountStatus; userAccountModel.CreationDate = DateTimeOffset.Parse(expectedCreationDate); userAccountModel.UpdationDate = DateTimeOffset.Parse(expectedUpdationDate); IUserAccountRepository userAccountRepository = new UserAccountRepository(new SQLServerGateway(), new ConnectionStringData()); //Act var timer = Stopwatch.StartNew(); await userAccountRepository.CreateAccount(userAccountModel); timer.Stop(); var actualExecutionTime = timer.ElapsedMilliseconds; Debug.WriteLine("Actual Execution Time: " + timer.Elapsed); //Assert Assert.IsTrue(actualExecutionTime <= expectedMaxExecutionTime); }
public async Task AddCode_AccountIdDoesntExists_ReturnTrue(string code, string expirationTime, int accountId, string username, string password, string salt, string emailAddress, string accountType, string accountStatus, string creationDate, string updationDate) { // Arrange IDataGateway dataGateway = new SQLServerGateway(); IConnectionStringData connectionString = new ConnectionStringData(); IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString); IUserAccountCodeRepository userAccountCodeRepository = new UserAccountCodeRepository(dataGateway, connectionString); var userAccountModel = new UserAccountModel(); userAccountModel.Id = accountId; userAccountModel.Username = username; userAccountModel.Password = password; userAccountModel.Salt = salt; userAccountModel.EmailAddress = emailAddress; userAccountModel.AccountType = accountType; userAccountModel.AccountStatus = accountStatus; userAccountModel.CreationDate = DateTimeOffset.Parse(creationDate); userAccountModel.UpdationDate = DateTimeOffset.Parse(updationDate); await userAccountRepository.CreateAccount(userAccountModel); var expectedResult = true; IUserAccountCodeService userAccountCodeService = new UserAccountCodeService(userAccountCodeRepository); // Act var actualResult = await userAccountCodeService.AddCode(code, DateTimeOffset.Parse(expirationTime), accountId); // Assert Assert.IsTrue(actualResult == expectedResult); }
private async Task <IActionResult> SetCookiesAndReturnViewOnLoginSuccess(UserAccountModel userAccountReturn, List <UserRolesModel> userRoles) { List <Claim> claims = new List <Claim> { new Claim(ClaimTypes.Name, userAccountReturn.LastName + " " + userAccountReturn.FirstName), new Claim("http://example.org/claims/UserName", "UserName", userAccountReturn.UserName), new Claim("http://example.org/claims/FirstName", "FirstName", userAccountReturn.FirstName), new Claim("http://example.org/claims/LastName", "LastName", userAccountReturn.LastName), new Claim(ClaimTypes.NameIdentifier, userAccountReturn.UserId.ToString()), new Claim("http://example.org/claims/LoggedInTime", "LoggedInTime", DateTime.Now.ToString()), new Claim(ClaimTypes.Email, userAccountReturn.Email), new Claim("http://example.org/claims/CookieUniqueId", "CookieUniqueId", userAccountReturn.CookieUniqueId.ToString()), }; if (userRoles != null && userRoles.Count > 0) { foreach (var item in userRoles) { claims.Add(new Claim(ClaimTypes.Role, item.RoleName)); } } var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); // create principal ClaimsPrincipal principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return(Json(new { newUrl = Url.Action("Index", "DashBoard", new { area = "DashBoard" }) })); }
public ActionResult Login(UserAccountModel usuario) { DataTable usuarioObtenido = new DataTable(); try { using (SqlConnection conexion = new SqlConnection(stringConnection)) { conexion.Open(); string sqlQuery = "SELECT [UserId],[FirstName],[SecondName],[LastName],[Code],[Email],[UserName],[Password],[AdmissionDate],[Status] FROM [dbo].[UserAccount] " + "where UserName = @UserName and Password = @Password; "; SqlDataAdapter sqlData = new SqlDataAdapter(sqlQuery, conexion); sqlData.SelectCommand.Parameters.AddWithValue("@UserName", usuario.UserName); sqlData.SelectCommand.Parameters.AddWithValue("@Password", usuario.Password); sqlData.Fill(usuarioObtenido); } if (usuarioObtenido.Rows.Count == 1) { Session["UserId"] = (usuarioObtenido.Rows[0][0].ToString()); Session["UserName"] = (usuarioObtenido.Rows[0][6].ToString()); return(RedirectToAction("LoggedIn")); } else { ModelState.AddModelError("", "Usuario o Password Incorrecta"); } } catch { } return(View()); }
public void ConvertTo_WebAccountToUserAccount_ConvertedObjectHasAccurateData(int expectedId, string expectedUsername, string expectedEmailAddress, AccountType expectedAccountType, AccountStatus expectedAccountStatus) { // Arrange DateTimeOffset expectedDate = DateTimeOffset.UtcNow; WebUserAccountModel webUserAccountModel = new WebUserAccountModel(); webUserAccountModel.Id = expectedId; webUserAccountModel.Username = expectedUsername; webUserAccountModel.EmailAddress = expectedEmailAddress; webUserAccountModel.AccountType = expectedAccountType.ToString(); webUserAccountModel.AccountStatus = expectedAccountStatus.ToString(); webUserAccountModel.CreationDate = expectedDate; webUserAccountModel.UpdationDate = expectedDate; UserAccountModel userAccountModel = new UserAccountModel(); // Act var convertedUserAccountModel = ModelConverterService.ConvertTo(webUserAccountModel, userAccountModel); // Assert Assert.IsTrue ( convertedUserAccountModel.Id == expectedId && convertedUserAccountModel.Username == expectedUsername && convertedUserAccountModel.Password == null && convertedUserAccountModel.Salt == null && convertedUserAccountModel.EmailAddress == expectedEmailAddress && convertedUserAccountModel.AccountType == expectedAccountType.ToString() && convertedUserAccountModel.AccountStatus == expectedAccountStatus.ToString() && convertedUserAccountModel.CreationDate == expectedDate && convertedUserAccountModel.UpdationDate == expectedDate ); }
public ActionResult EditUserAccount(string id) { using (ServiceProxy <IUserService> proxy = new ServiceProxy <IUserService>()) { var user = proxy.Channel.GetUserByKey(new Guid(id), QuerySpec.VerboseOnly); var model = UserAccountModel.CreateFromDataObject(user); var roles = proxy.Channel.GetRoles(); if (roles == null) { roles = new RoleDataObjectList(); } roles.Insert(0, new RoleDataObject { ID = Guid.Empty.ToString(), Name = "(未指定)", Description = "(未指定)" }); if (model.Role != null) { ViewData["roles"] = new SelectList(roles, "ID", "Name", model.Role.ID); } else { ViewData["roles"] = new SelectList(roles, "ID", "Name", Guid.Empty.ToString()); } return(View(model)); } }
public ActionResult Register(UserAccountModel usuarioNuevo) { if (ModelState.IsValid) { try { using (SqlConnection conexion = new SqlConnection(stringConnection)) { conexion.Open(); string sqlInsert = "INSERT INTO [dbo].[UserAccount]([FirstName],[SecondName],[LastName],[Email],[UserName],[Password]) " + "VALUES(@FirstName, @SecondName, @LastName, @Email, @UserName, @Password)"; SqlCommand comando = new SqlCommand(sqlInsert, conexion); comando.Parameters.AddWithValue("@FirstName", usuarioNuevo.FirstName); comando.Parameters.AddWithValue("@SecondName", usuarioNuevo.SecondName); comando.Parameters.AddWithValue("@LastName", usuarioNuevo.LastName); comando.Parameters.AddWithValue("@Email", usuarioNuevo.Email); comando.Parameters.AddWithValue("@UserName", usuarioNuevo.UserName); comando.Parameters.AddWithValue("@Password", usuarioNuevo.Password); comando.ExecuteNonQuery(); } ModelState.Clear(); ViewBag.Message = usuarioNuevo.FirstName + " " + usuarioNuevo.SecondName + " " + usuarioNuevo.LastName + " registrado exitosamente."; } catch { } } return(RedirectToAction("Index", "Home")); }
public async Task ChangePasswordTest_UserPasswordChanges_PasswordChangeCompletes(int userId, string password, string newPassword) { IDataGateway dataGateway = new SQLServerGateway(); IConnectionStringData connectionString = new ConnectionStringData(); IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString); IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString); ICryptographyService cryptographyService = new CryptographyService(userAccountRepository); IAuthenticationService authenticationService = new AuthenticationService(userAccountRepository); IAccountSettingsService userAccountSettingsManager = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService); bool result = await userAccountSettingsManager.ChangePasswordAsync(password, newPassword, userId); if (!result) { Assert.IsTrue(false); } UserAccountModel model = await userAccountRepository.GetAccountById(userId); UserAccountRepository userAccountRepo = new UserAccountRepository(new SQLServerGateway(), new ConnectionStringData()); string encryptedNewPassword = await cryptographyService.EncryptPasswordAsync(newPassword, userId); if (model.Password == encryptedNewPassword) { Assert.IsTrue(true); } else { Assert.IsTrue(false); } }
public async Task ChangeEmail_UserEmailChanges_EmailChangeCompletes(int userId, string password, string email) { IDataGateway dataGateway = new SQLServerGateway(); IConnectionStringData connectionString = new ConnectionStringData(); IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString); IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString); ICryptographyService cryptographyService = new CryptographyService(userAccountRepository); IAuthenticationService authenticationService = new AuthenticationService(userAccountRepository); IAccountSettingsService userAccountSettingsManager = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService); bool result = await userAccountSettingsManager.ChangeEmailAsync(password, email, userId); if (!result) { Assert.IsTrue(false); } UserAccountModel model = await userAccountRepository.GetAccountById(userId); if (model.EmailAddress == email) { Assert.IsTrue(true); } else { Assert.IsTrue(false); } }
public async Task DeleteAccountByUserIDAsync_UserAccountIsDelted_UserAccountSuccessfulyDeletes(int userId, string password) { IDataGateway dataGateway = new SQLServerGateway(); IConnectionStringData connectionString = new ConnectionStringData(); IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString); IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString); ICryptographyService cryptographyService = new CryptographyService(userAccountRepository); IAuthenticationService authenticationService = new AuthenticationService(userAccountRepository); IAccountSettingsService userAccountSettingsManager = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService); bool result = await userAccountSettingsManager.DeleteAccountByUserIDAsync(userId, password); if (!result) { Assert.IsTrue(false); } UserAccountModel model = await userAccountRepository.GetAccountById(userId); if (model.AccountStatus == "Deleted") { Assert.IsTrue(true); } else { Assert.IsTrue(false); } }
public void Add(UserAccountModel model) { var doc = new UserAccount { UniqueId = Guid.NewGuid().ToString(), Username = model.Username, HashedPassword = model.HashedPassword, }; model.LinkedAccounts .Select(la => new LinkedAccount { ClaimedIdentifier = la.ClaimedIdentifier, ProviderName = la.ProviderName, ProviderUri = la.ProviderUri }) .ToList().ForEach(doc.LinkedAccounts.Add); model.ClientCertificates .Select(c => new ClientCertificate() { Thumbprint = c.Thumbprint, Description = c.Description }) .ToList().ForEach(doc.ClientCertificates.Add); }
public JsonResult Save(UserAccountModel user) { string serverResponse = ""; if (user != null) { if (IsNull(user.Username)) { serverResponse = "Username is required"; } else if (IsNull(user.Firstname)) { serverResponse = "First Name is required"; } else if (IsNull(user.LastName)) { serverResponse = "Last name is required"; } else if (IsNull(user.Type)) { serverResponse = "Type is required"; } else { UserService.Save(user, out serverResponse); } } else { serverResponse = "Fill up all required fields"; } return(Json(serverResponse)); }
private async void UserLogin() { var isEmpty = ValidateFields(LoginModel.UserUsername, LoginModel.UserPassword); if (!isEmpty) { return; } MemberServiceProvider memberService = new MemberServiceProvider(); UserAccountModel userAccountModel = new UserAccountModel(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); userAccountModel.Username = LoginModel.UserUsername; userAccountModel.Password = LoginModel.UserPassword; try { var result = await memberService.AuthenticateUserAsync(userAccountModel, cancellationTokenSource.Token); if (result != null) { MainDashboard mainDashboard = new MainDashboard(); App.Current.MainWindow.Close(); mainDashboard.Owner = App.Current.MainWindow; mainDashboard.ShowDialog(); ClearFields(); } } catch (Exception ex) { ShowGenericMessage(ex.Message); } }
public async Task CreateAccount_UsernameAndEmailDontExist_AccountExistsId(int expectedId, string username, string password, string salt, string emailAddress, string accountType, string accountStatus, string creationDate, string updationDate) { //Arrange UserAccountModel userAccountModel = new UserAccountModel(); userAccountModel.Id = expectedId; userAccountModel.Username = username; userAccountModel.Password = password; userAccountModel.Salt = salt; userAccountModel.EmailAddress = emailAddress; userAccountModel.AccountType = accountType; userAccountModel.AccountStatus = accountStatus; userAccountModel.CreationDate = DateTimeOffset.Parse(creationDate); userAccountModel.UpdationDate = DateTimeOffset.Parse(updationDate); IUserAccountRepository userAccountRepository = new UserAccountRepository(new SQLServerGateway(), new ConnectionStringData()); //Act await userAccountRepository.CreateAccount(userAccountModel); var actualAccount = await userAccountRepository.GetAccountById(expectedId); //Assert Assert.IsTrue(actualAccount.Id == expectedId); }
public RegistrationStatus RegisterAccount(RegistrationRequest request, out ComplexUserAccount registeredAcc) { UserAccountModel existingAccount = FindByName(request.UserName); if (existingAccount != null) { registeredAcc = null; return(RegistrationStatus.AlreadyExists); } var newAccount = new ComplexUserAccount { Name = request.UserName }; Password passwordData = passwordService.CreatePasswordData(request.Password); passwordData.ParentId = newAccount.Id; newAccount.PasswordDatas.Add(passwordData); RegistrationStatus result = RegisterAccount(newAccount, out newAccount); registeredAcc = newAccount; registeredAcc.PasswordData = registeredAcc.PasswordDatas.First(); return(result); }
public async Task Init() { await TestCleaner.CleanDatabase(); var numTestRows = 20; IDataGateway dataGateway = new SQLServerGateway(); IConnectionStringData connectionString = new ConnectionStringData(); IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString); for (int i = 1; i <= numTestRows; ++i) { UserAccountModel userAccountModel = new UserAccountModel(); userAccountModel.Id = i; userAccountModel.Username = "******" + i; userAccountModel.Password = "******" + i; userAccountModel.Salt = "TestSalt" + i; userAccountModel.EmailAddress = "TestEmailAddress" + i; userAccountModel.AccountType = "TestAccountType" + i; userAccountModel.AccountStatus = "TestAccountStatus" + i; userAccountModel.CreationDate = DateTimeOffset.UtcNow; userAccountModel.UpdationDate = DateTimeOffset.UtcNow; await userAccountRepository.CreateAccount(userAccountModel); } }
public async Task <IActionResult> GetLoggedInUserDetails() { LoggedInUserDetailsViewModel loggedInUserDetailsViewModel = await GetUserDetailsFromCookies(); UserAccountModel userAccountModel = _mapper.Map <UserAccountModel>(loggedInUserDetailsViewModel); var userLoginDetails = this._IUserAccountService.GetUserDetailsForLastLogin(userAccountModel); loggedInUserDetailsViewModel.LastLoggedInUserDetailsViewModel = new LoggedInUserDetailsViewModel(); loggedInUserDetailsViewModel.CurrentLoggedInUserDetailsViewModel = new LoggedInUserDetailsViewModel(); IpPropertiesModal ipPropertiesModal = new IpPropertiesModal(); string ipAddress = this._IHttpContextAccessor .HttpContext.Connection.RemoteIpAddress .ToString(); ipPropertiesModal = this._IAppAnalyticsService.GetIpAddressDetails(ipAddress); loggedInUserDetailsViewModel.LastLoggedInUserDetailsViewModel = _mapper.Map <LoggedInUserDetailsViewModel>(userLoginDetails.LastSessionDetails); loggedInUserDetailsViewModel.CurrentLoggedInUserDetailsViewModel = _mapper.Map <LoggedInUserDetailsViewModel>(userLoginDetails.CurrentSessionDetails); string partialViewHtml = await this.RenderViewAsync("_LoggedInUserDetails", loggedInUserDetailsViewModel, true); return(Json(partialViewHtml)); }
public long UpdateUser(UserAccountModel model) { long res = 0; // Declare new DataAccess object UserAccountDa dataAccess = new UserAccountDa(); using (var transaction = new TransactionScope()) { TblUserAccount entity = new TblUserAccount(); entity.USER_ID = model.USER_ID = model.USER_ID_HIDDEN; entity.USER_NAME = model.USER_NAME; entity.SHOP_NAME = model.SHOP_NAME; entity.AREA = model.AREA; entity.USER_CITY = model.USER_CITY; entity.USER_DISTRICT = model.USER_DISTRICT; entity.USER_TOWN = model.USER_TOWN; entity.USER_ADDRESS = model.USER_ADDRESS; entity.USER_PHONE = model.USER_PHONE; entity.INS_DATE = Utility.GetCurrentDateTime(); entity.PASSWORD_LAST_UPDATE_DATE = Utility.GetCurrentDateTime(); entity.UPD_DATE = Utility.GetCurrentDateTime(); res = dataAccess.UpdateUser(entity); if (res <= 0) { transaction.Dispose(); } transaction.Complete(); } return(res); }
public async Task Init() { IDataGateway dataGateway = new SQLServerGateway(); IConnectionStringData connectionString = new ConnectionStringData(); IUserAccountSettingsRepository userAccountSettingsRepository = new UserAccountSettingRepository(dataGateway, connectionString); var settings = await userAccountSettingsRepository.GetAllSettings(); foreach (var setting in settings) { await userAccountSettingsRepository.DeleteUserAccountSettingsByUserId(setting.UserId); } await DataAccessTestHelper.ReseedAsync("UserAccountSettings", 0, connectionString, dataGateway); IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString); var accounts = await userAccountRepository.GetAllAccounts(); foreach (var account in accounts) { await userAccountRepository.DeleteAccountById(account.Id); } await DataAccessTestHelper.ReseedAsync("UserAccount", 0, connectionString, dataGateway); int i = 1; UserAccountModel userAccountModel = new UserAccountModel(); userAccountModel.Id = i; userAccountModel.Username = "******" + i; userAccountModel.Password = "" + i; userAccountModel.Salt = "" + i; userAccountModel.EmailAddress = "TestEmailAddress" + i; userAccountModel.AccountType = "TestAccountType" + i; userAccountModel.AccountStatus = "TestAccountStatus" + i; userAccountModel.CreationDate = DateTimeOffset.UtcNow; userAccountModel.UpdationDate = DateTimeOffset.UtcNow; await userAccountRepository.CreateAccount(userAccountModel); UserAccountRepository userAccountRepo = new UserAccountRepository(new SQLServerGateway(), new ConnectionStringData()); ICryptographyService cryptographyService = new CryptographyService(userAccountRepo); await cryptographyService.newPasswordEncryptAsync("Password", 1); UserAccountSettingsModel userAccountSettingsModel = new UserAccountSettingsModel(); userAccountSettingsModel.Id = 0; userAccountSettingsModel.UserId = 1; userAccountSettingsModel.FontSize = 12; userAccountSettingsModel.FontStyle = "Time New Roman"; userAccountSettingsModel.ThemeColor = "White"; IAuthenticationService authenticationService = new AuthenticationService(userAccountRepository); IAccountSettingsService userAccountSettingsManager = new AccountSettingsService(userAccountRepository, userAccountSettingsRepository, cryptographyService, authenticationService); await userAccountSettingsManager.CreateUserAccountSettingsAsync(userAccountSettingsModel); }
public async Task <ActionResult <NonUserProfileData> > GetOtherData([FromBody] int userId) { var token = ExtractHeader(HttpContext, "Authorization", ',', 1); var claims = new List <BusinessModels.UserAccessControl.UserClaimModel>(); var accessPolicy = _authorizationPolicyManager.ConfigureCustomPolicy(new List <string>() { "application:read", }, claims); if (!_authorizationResolutionManager.Authorize(token, accessPolicy)) { return(StatusCode(403)); } try { NonUserProfileData model = new NonUserProfileData(); UserAccountModel userAccountModel = await _userAccountRepository.GetAccountById(userId); model.Username = userAccountModel.Username; string[] dates = userAccountModel.CreationDate.ToString().Split(" "); model.JoinDate = dates[0]; return(Ok(model)); } catch { return(StatusCode(404)); } }
public IHttpActionResult ResetPasssword(ResetUserPassword model) { ResponseBaseCommon response = new ResponseBaseCommon() { IsSuccess = true, MessageCode = (int)ApiBaseErrorCode.API_SUCCESS, MessageContent = ApiBaseErrorCode.API_SUCCESS.ToString() }; if (string.IsNullOrWhiteSpace(model.Guid)) { response.IsSuccess = false; response.MessageCode = (int)ApiBaseErrorCode.API_PARAM_ERROR; response.MessageContent = "必要参数缺失,请检查"; return(Ok(response)); } UserAccountModel content = usermanager.GetUser(model.Guid); content.UserPswd = BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes("fujica"))).Replace("-", ""); if (!usermanager.ModifyUser(content)) { response.IsSuccess = false; response.MessageCode = (int)ApiBaseErrorCode.API_FAIL; response.MessageContent = usermanager.LastErrorDescribe; //ApiBaseErrorCode.API_FAIL.ToString(); } return(Ok(response)); }
/* * To Do: * -Password without banned charactes */ public async Task <IActionResult> Register(RegisterUserModel model) { var anotherUser = await _db.Users.FirstOrDefaultAsync(x => x.UserName == model.Login || x.Email == model.Email); if (anotherUser == null) { UserAccountModel newUser = new UserAccountModel { Id = Math.Abs(Guid.NewGuid().GetHashCode()), UserName = model.Login, Password = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes(model.Password) ), Email = model.Email, AdminPrivilage = model.AdminPrivilage ?? false }; await _db.AddAsync(newUser); await _db.SaveChangesAsync(); return(View("index")); } return(View("Register")); }
public async Task <ActionResult <bool> > CreateFriendRequest([FromBody] IdUsernameModel ids) { try { var token = ExtractHeader(HttpContext, "Authorization", ',', 1); var claims = new List <UserClaimModel>(); claims.Add(new UserClaimModel("Id", ids.UserId.ToString())); var accessPolicy = _authorizationPolicyManager.ConfigureCustomPolicy(new List <string>() { "friends_list:write", }, claims); if (!_authorizationResolutionManager.Authorize(token, accessPolicy)) { return(StatusCode(403)); } UserAccountModel model = await _userAccountRepository.GetAccountByUsername(ids.FriendUsername); int friendId = model.Id; await _friendListManager.RequestFriendAsync(friendId, ids.UserId); return(Ok(true)); } catch { return(StatusCode(404)); } }
public ActionResult Register(UserAccountViewModel registrationView) { UserAccountModel userAccountModel = new UserAccountModel(); bool statusRegistration = false; string messageRegistration = string.Empty; if (ModelState.IsValid) { Mapper.Map(registrationView, userAccountModel); DatabaseModel databaseInfoModel = new DatabaseModel(); databaseInfoModel.UserName = "******" + userAccountModel.UserName; databaseInfoModel = this._IUserAccountOrchestrator.AddNewUser(userAccountModel, databaseInfoModel); GlobalCachingProvider.Instance.RemoveUserCacheItems(); GlobalCachingProvider.Instance.GetAllUsersAccountsToCache(); messageRegistration = "Your account has been created successfully. ^_^"; statusRegistration = true; } else { messageRegistration = "Something Wrong!"; } ViewBag.Message = messageRegistration; ViewBag.Status = statusRegistration; return(View(registrationView)); }
public UserAccountPresenter() : base() { _userAccountModel = new UserAccountModel(); RegisterToEventBus(); }
public UserAccountModel ValidateUserLoginDetails(UserAccountModel userAccountModel) { UserAccountModel userAccount = new UserAccountModel(); userAccount = this._IUserAccountRepository.ValidateUserLoginDetails(userAccountModel); return(userAccount); }
private void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (HasStateChanged) { // check for an existing entry _userAccount = _userAccountService.FetchByUsername(_userName); if (_userAccount == null) { // Create the account _userAccountService.Create(new CreateUserAccountModel() { Firstname = "", Lastname = "", Username = _userName, CachedData = Serialize(), UpdateDate = DateTime.Now }); } else { // Update the account _userAccount.CachedData = this.Serialize(); _userAccount.UpdateDate = DateTime.Now; _userAccountService.UpdateCacheData(_userAccount); } HasStateChanged = false; } }
private bool fcnLogin(LoginModel model, ref User user, ref UserAccountInformation userAccountInfo, int LoginOrReset) { ValidateUserLogin objValidateUserLogin = null; // main class LoginUserMiscInfo objLoginUserMiscInfo = null; // Login validate information UserModel ObjUser = null; UserAccountModel ObjUserAccount = null; string strUsername = model.UserName; string strPassword = model.ResetPassword = model.Password; bool blnLogin = false; //added BY Rakesh Kumar on 13 June 2013 LoginUserData try { objValidateUserLogin = new ValidateUserLogin(); // main class objLoginUserMiscInfo = new LoginUserMiscInfo(); // Login validate information ObjUser = new UserModel(); ObjUserAccount = new UserAccountModel(); // UserAccount information objValidateUserLogin = _loginService.ValidateUserLogin(model.UserName.Trim(), model.Password.Trim(), LoginOrReset, "http://www.newspaperarchive.com", Session.SessionID);////third parameter 0 is for Reset login . //if (objValidateUserLogin != null) if (objValidateUserLogin.User != null && objValidateUserLogin.FBUser != null && objValidateUserLogin.UserAccount != null && objValidateUserLogin.LoginUserMiscInfo != null) { objLoginUserMiscInfo = objValidateUserLogin.LoginUserMiscInfo; ObjUser = objValidateUserLogin.User; ObjUserAccount = objValidateUserLogin.UserAccount; if (ObjUser != null && objLoginUserMiscInfo != null && ObjUserAccount != null) blnLogin = true; } if (blnLogin) { int? LoggedInStatus = objLoginUserMiscInfo.UserIsLive; //var CheckEncryptedLoginCookie = GetCookieValue(".ASPXAUTH"); //Added By Rakesh //if (LoggedInStatus > 0 && string.IsNullOrEmpty(CheckEncryptedLoginCookie)) if (LoggedInStatus > 0) { model.loginMessage = "<div class=\"alert-panel\"><div class=\"alert alert-error\"><button data-dismiss=\"alert\" class=\"close\" type=\"button\">×</button>" + "<b>User already logged in at: " + String.Format("{0:MMM d yyyy}", objLoginUserMiscInfo.LoginTime) + ". Your account is showing you are logged in. More than one person can not be logged in under " + "the same username. Please click on the \"Yes. Log me in and end the other session.\" button.</b></div></div>"; //////////"the same username. Please re-enter your user name and password then click on the reset button.</b></div></div>"; model.isConcurrent = true; blnLogin = false; return blnLogin; } HttpCookie cookies = new HttpCookie(_config.GetStringValueFromConfig("cookiePrefix", "NewspaperARCHIVE.com") + ".shoppingCart"); cookies = Request.Cookies[_config.GetStringValueFromConfig("cookiePrefix", "NewspaperARCHIVE.com") + ".shoppingCart"]; if (cookies != null) { cookies.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookies); } //userAccountInfo = _userAccountService.GetActiveAccountByUserId(user.UserId); Na.Core.Cookies.clsCookies clsCookie = new Na.Core.Cookies.clsCookies(); if (objLoginUserMiscInfo == null) { blnLogin = false; } else { // var RoleId = 0; if (objLoginUserMiscInfo.WebsiteID == 1 && objLoginUserMiscInfo.ActiveAccount == 1) { //roleId = Convert.ToInt32(objLoginInformatin.RoleId); //var websiteRole = _webRoles.GetWebsiteRoleById(roleId); String WebsiteRoleName = objLoginUserMiscInfo.WebsiteRoleName; // if Role Name exists then Proceed ahead else escape this conditions if (!string.IsNullOrEmpty(WebsiteRoleName)) { if (ObjUserAccount.EndDate < DateTime.Now) { Response.Cookies.Add(clsCookie.fcnCreateValidationCookie(Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.UserId.ToString()), Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.Password), Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.UserName), objLoginUserMiscInfo.EmailAddress, ObjUser.FirstName, ObjUser.LastName, "7", "Expired", _common.GetStringValue(ObjUserAccount.PlanId, string.Empty), "", ConfigurationManager.AppSettings["cookieTimeout"].ToString(), ConfigurationManager.AppSettings["cookiePrefix"].ToString())); } else { Response.Cookies.Add(clsCookie.fcnCreateValidationCookie(Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.UserId.ToString()), Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.Password), Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.UserName), objLoginUserMiscInfo.EmailAddress, ObjUser.FirstName, ObjUser.LastName, ObjUserAccount.RoleId.ToString(), objLoginUserMiscInfo.WebsiteRoleName, _common.GetStringValue(ObjUserAccount.PlanId, string.Empty), "", ConfigurationManager.AppSettings["cookieTimeout"].ToString(), ConfigurationManager.AppSettings["cookiePrefix"].ToString())); } // int? webSiteIdForURL = objLoginUserMiscInfo.WebSiteIdForReport; //// below functionality is handled by Sproc--by Rakesh Kumar on Dated 13 june 2013 // _userService.ReportUserLogin(objLoginInformatin.UserID, "http://www.newspaperarchive.com", Session.SessionID); } } else { //if (objLoginUserMiscInfo.ActiveAccount >= 0) //{ // Response.Cookies.Add(clsCookie.fcnCreateValidationCookie(Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.UserId.ToString()), Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.Password), Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.UserName), objLoginUserMiscInfo.EmailAddress, ObjUser.FirstName, ObjUser.LastName, "7", "Expired", _common.GetStringValue(ObjUserAccount.PlanId, string.Empty), "", ConfigurationManager.AppSettings["cookieTimeout"].ToString(), ConfigurationManager.AppSettings["cookiePrefix"].ToString())); // blnLogin = true; //} //else //{ Response.Cookies.Add(clsCookie.fcnCreateValidationCookie(Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.UserId.ToString()), Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.Password), Na.Core.Helpers.SecureNPASecurity.Encryption.EncryptText(ObjUser.UserName), objLoginUserMiscInfo.EmailAddress, ObjUser.FirstName, ObjUser.LastName, "7", "Expired", _common.GetStringValue(ObjUserAccount.PlanId, string.Empty), "", ConfigurationManager.AppSettings["cookieTimeout"].ToString(), ConfigurationManager.AppSettings["cookiePrefix"].ToString())); blnLogin = true; //} } } } else { blnLogin = false; Redirect(Na.Core.Configuration.NaConfig.Url.DomainUrl + "/login?value=invalid"); } if (blnLogin) { Session["testUSer"] = model.UserName; UpdateSharedLoggedInUserInfo(objValidateUserLogin); } } //catch (Exception) { } finally { objLoginUserMiscInfo = null; ObjUser = null; ObjUserAccount = null; objValidateUserLogin = null; } return blnLogin; }