protected void Page_Load( object sender, EventArgs e ) { if ( string.IsNullOrEmpty ( txtUserName.Text ) || string.IsNullOrEmpty ( txtPassword.Text ) ) { UserLoginSection _userLoginSection = ( UserLoginSection ) ConfigurationManager.GetSection ( "userLoginGroup/userLogin" ); if ( _userLoginSection != null ) { _configUser = new UserLogin () { Login = _userLoginSection.UserLogin, Password = _userLoginSection.UserPassword }; } } else { _configUser = new UserLogin () { Login = txtUserName.Text, Password = txtPassword.Text }; } // Note: Add code to validate user name, password. This code is for illustrative purpose only. // Do not use it in production environment.) if ( IsAuthentic ( _configUser ) ) { if ( Request.QueryString [ "ReturnUrl" ] != null ) { FormsAuthentication.RedirectFromLoginPage ( _configUser.Login, false ); } else { FormsAuthentication.SetAuthCookie ( _configUser.Login, false ); Response.Redirect ( "default.aspx" ); } } }
/// <summary> /// Sets the password from rest. /// </summary> /// <param name="value">The value.</param> private void SetPasswordFromRest( UserLogin value ) { UserLoginWithPlainTextPassword userLoginWithPlainTextPassword = null; string json = string.Empty; this.ActionContext.Request.Content.ReadAsStreamAsync().ContinueWith( a => { // to allow PUT and POST to work with either UserLogin or UserLoginWithPlainTextPassword, read the the stream into a UserLoginWithPlainTextPassword record to see if that's what we got a.Result.Position = 0; StreamReader sr = new StreamReader( a.Result ); json = sr.ReadToEnd(); userLoginWithPlainTextPassword = JsonConvert.DeserializeObject( json, typeof( UserLoginWithPlainTextPassword ) ) as UserLoginWithPlainTextPassword; } ).Wait(); if ( userLoginWithPlainTextPassword != null ) { // if a UserLoginWithPlainTextPassword was posted, and PlainTextPassword was specified, encrypt it and set UserLogin.Password if ( !string.IsNullOrWhiteSpace( userLoginWithPlainTextPassword.PlainTextPassword ) ) { ( this.Service as UserLoginService ).SetPassword( value, userLoginWithPlainTextPassword.PlainTextPassword ); } } else { // since REST doesn't serialize Password, get the existing Password from the database so that it doesn't get NULLed out var existingUserLoginRecord = this.Get( value.Id ); if (existingUserLoginRecord != null) { value.Password = existingUserLoginRecord.Password; } } }
protected BaseViewModel(IMessenger messenger, UserLogin userLogin) { Messenger = messenger; Initialize(); if (UserLogin == null) UserLogin = userLogin; }
protected void changeUsername_Click(object sender, EventArgs e) { Guid uid = new Guid(Session["UserID"].ToString()); UserLogin checkit = UserLogin_S.Loging(newUsername.Text); if (checkit == null) { UserLogin newUser = new UserLogin(); newUser.UserName = newUsername.Text; newUser.UserId = uid; bool upd = UserLogin_S.ResetUsername(newUser); if (upd == true) { green0.Text = "Updated"; Session["UserName"] = newUsername.Text; username.Text = newUsername.Text; } else { green0.Text = "Something went wrong!"; } valid.Text = ""; } else { valid.Text = "Not-Available"; green0.Text = ""; } }
// PUT odata/UserLogin(5) public virtual async Task<IHttpActionResult> Put([FromODataUri] string providerKey, UserLogin userLogin) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (providerKey != userLogin.ProviderKey) { return BadRequest(); } try { await MainUnitOfWork.UpdateAsync(userLogin); } catch (DbUpdateConcurrencyException) { if (!MainUnitOfWork.Exists(providerKey)) { return NotFound(); } else { return Conflict(); } } return Ok(userLogin); }
protected void resetPassword_Click(object sender, EventArgs e) { Guid uid = new Guid(Session["UserID"].ToString()); UserLogin checkit = UserLogin_S.NewLoging(username.Text, psHidOld.Value); if (checkit != null) { UserLogin newPwdUser = new UserLogin(); newPwdUser.Password = psHid.Value; newPwdUser.UserId = uid; newPwdUser.PasswordStatus = "done"; bool upd = UserLogin_S.ResetPassword(newPwdUser); if (upd == true) { green1.Text = "Updated"; } else { green1.Text = "Something went wrong!"; } pwdCheck.Text = ""; } else { pwdCheck.Text = "Wrong-Password"; green1.Text = ""; } }
public void Setup() { Directory.SetCurrentDirectory(TestContext.CurrentContext.TestDirectory); if (Directory.Exists(LoginEventStore.EventStorePath)) { Directory.Delete(LoginEventStore.EventStorePath, true); } sut = new UserLogin(); }
private bool IsAuthentic( UserLogin userLogin ) { if ( userLogin == null ) return false; bool valid = _authenticatedUsers.Any ( u => ( u.Login == userLogin.Login && u.Password == userLogin.Password ) ); return valid; }
public ApollosUserLogin( UserLogin userLogin ) { Guid = userLogin.Guid; Id = userLogin.Id; PersonId = userLogin.PersonId; ApollosHash = userLogin.Password; UserName = userLogin.UserName; }
public LoginUser() { _userLogin = new UserLogin(); _client.UserLoginCompleted += new EventHandler<UserLoginCompletedEventArgs>(_client_UserLoginCompleted); _client.UserLoginOutCompleted += new EventHandler<UserLoginOutCompletedEventArgs>(_client_UserLoginOutCompleted); _client.GetSystemTypeByUserIDCompleted += new EventHandler<GetSystemTypeByUserIDCompletedEventArgs>(_client_GetSystemTypeByUserIDCompleted); }
public static UserLogin FromIUserLogin(IUserLogin i) { UserLogin l = new UserLogin(); l.LoginProvider = i.LoginProvider; l.ProviderDisplayName = i.ProviderDisplayName; l.ProviderKey = i.ProviderKey; l.SiteId = i.SiteId; l.UserId = i.UserId; return l; }
/// <summary> /// Authenticates the specified user name and password /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns></returns> public override bool Authenticate( UserLogin user, string password ) { string username = user.UserName; if ( !String.IsNullOrWhiteSpace( GetAttributeValue( "Domain" ) ) ) username = string.Format( @"{0}\{1}", GetAttributeValue( "Domain" ), user.UserName ); var context = new PrincipalContext( ContextType.Domain, GetAttributeValue( "Server" ) ); using ( context ) { return context.ValidateCredentials( user.UserName, password ); } }
public ActionResult Login(UserLogin model, string returnUrl) { if (!ModelState.IsValid) return ViewBase(DIALOG, "LoginForm", model); //User user = userService.ValidateUser(model.UserName, model.Password); //if (user != null) { User user = new User { Login = "******", Name = "qwerwer" }; SignInAsync(user, model.RememberMe); return RedirectBase("Index", "Home");// ViewBase("#loginButtons", "_LoginPartial"); //} ModelState.AddModelError("", "Неверное имя пользователя или пароль."); return ViewBase("#dialogsContainer", "LoginForm", model); }
protected void calculatePrint(UserLogin userData) { try { UserMapping map = UserMapping_S.MapUser(userData.UserId); if (map != null) { DateTime frDate = DateTime.ParseExact(fromDate.Value + ",000", "dd/MM/yyyy HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture); DateTime tDate = DateTime.ParseExact(toDate.Value + ",000", "dd/MM/yyyy HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture); if (frDate != null && tDate != null) { Utilities utFr = Utilitie_S.DateTimeToEpoch(frDate); Utilities utTo = Utilitie_S.DateTimeToEpoch(tDate); List<FetchingEnergy> energy = FetchingEnergy_s.fetchBillingData(utFr.Epoch, utTo.Epoch, map.MeterId, map.Apartment); if (energy != null) { float en = energy[1].FwdHr - energy[0].FwdHr; float untPrice = 3; decimal bill = Convert.ToDecimal(en * untPrice); bill = Math.Round(bill, 2); fullName.InnerText = userData.FullName; unitsConsumed.InnerText = (energy[1].FwdHr - energy[0].FwdHr).ToString(); address.InnerText = userData.Apartment; mobile.InnerText = userData.Mobile; meterNo.InnerText = map.Apartment + " - " + map.MeterId.ToString(); billPeriod.InnerText = frDate.ToString("dd-MMM-yyyy") + " - " + tDate.ToString("dd-MMM-yyyy"); unitRate.InnerText = untPrice.ToString() + " Rs/unit"; total.InnerText = bill.ToString(); billAmount.InnerHtml = "Bill Amount: Rs " + bill.ToString(); dueDate.InnerHtml = "Due Date: " + DateTime.Now.AddDays(15).ToString("dd-MMM-yyyy"); billNo.InnerText = "Rep " + meterNo.InnerText + " - " + DateTime.Today.ToString("dd-MMM-yyyy"); billDate.InnerText = DateTime.Now.ToString("dd-MMM-yyyy"); } } } } catch (Exception e) { } }
private void lazyinit() { repositoy = new ServiceRepository(); IService entity = null; entity = new GetUserInfo(); repositoy.storeServiceEntity(service_type.GET_USER_INFO, entity); entity = new RegistUser(); repositoy.storeServiceEntity(service_type.REGIST_USER, entity); entity = new UserLogin(); repositoy.storeServiceEntity(service_type.USER_LOGIN, entity); entity = new DeleteTravelDiary(); repositoy.storeServiceEntity(service_type.DELETE_TRAVEL_DIARY, entity); entity = new UpdateTravelDiary(); repositoy.storeServiceEntity(service_type.UPDATE_TRAVEL_DIARY, entity); entity = new PublishTravelDiary(); repositoy.storeServiceEntity(service_type.PUBLISH_TRAVEL_DIARY, entity); entity = new GetTravelDiariesList(); repositoy.storeServiceEntity(service_type.GET_TRAVEL_DIARYLIST, entity); entity = new GetTravelDiaryDetailInfo(); repositoy.storeServiceEntity(service_type.GET_TRAVEL_DIARY_DETAIL, entity); entity = new GetTravelComments(); repositoy.storeServiceEntity(service_type.GET_TRAVEL_COMMENT, entity); entity = new GetAssociatedProductsInfo(); repositoy.storeServiceEntity(service_type.GET_ASSOCIATED_PRODUCT, entity); entity = new GetCategory(); repositoy.storeServiceEntity(service_type.GET_DISPLAY_CATEGORY, entity); entity = new CollectTravelDiary(); repositoy.storeServiceEntity(service_type.COLLECT_TRAVEL_DIARY, entity); entity = new ReserveProduct(); repositoy.storeServiceEntity(service_type.RESERVE_PRODUCT, entity); return; }
public async Task<IHttpActionResult> Register(UserLogin userModel) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await _repo.RegisterUser(userModel); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return errorResult; } return Ok(); }
public void Create() { // Saving changes using the session API using (IDocumentSession session = documentStore.OpenSession()) { // Operations against session Party p = new Party(); UserLogin userLogin = new UserLogin(); userLogin.Username = "******"; userLogin.Password = "******"; userLogin.party = p; session.Store(p); session.Store(userLogin); // Flush those changes session.SaveChanges(); } Console.WriteLine("Completed"); }
public static bool AddUserLogin(string connectionString, UserLogin userLogin) { try { using (var context = new UserLoginDBContext(connectionString)) { context.UserLogins.Add(userLogin); var result = context.SaveChanges(); return result > 0; } } catch (Exception exception) { NLogLogger.LogError(exception, TitleResources.Error, ExceptionResources.ExceptionOccured, ExceptionResources.ExceptionOccuredLogDetail); return false; } }
public HttpResponseMessage Login(UserLogin login) { HttpResponseMessage response = new HttpResponseMessage(); response.StatusCode = System.Net.HttpStatusCode.Unauthorized; if (login != null) { int? userId; if (_userService.ValidateUserLogin(login.UserName, login.Password, out userId)) { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, userId.ToString())); OwinHttpRequestMessageExtensions.GetOwinContext(this.Request).Authentication. SignIn(identity); response.StatusCode = System.Net.HttpStatusCode.OK; response.Content = new StringContent("Success"); } } return response; }
/// <summary> /// Authenticates the specified user name and password /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns></returns> public override bool Authenticate( UserLogin user, string password ) { var passwordIsCorrect = CheckF1Password( user.UserName, password ); if ( passwordIsCorrect ) { using ( var rockContext = new RockContext() ) { var userLoginService = new UserLoginService( rockContext ); var userFromService = userLoginService.Get( user.Id ); var databaseGuid = Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid(); userFromService.EntityTypeId = EntityTypeCache.Read( databaseGuid ).Id; userLoginService.SetPassword( userFromService, password ); rockContext.SaveChanges(); } } return passwordIsCorrect; }
protected void saving_Click(object sender, EventArgs e) { UserLogin updateProfile = new UserLogin(); updateProfile.EMail = email.Text; updateProfile.FullName = fullname.Text; updateProfile.Mobile = contact.Text; updateProfile.UserId =new Guid( Session["UserID"].ToString()); bool stc = UserLogin_S.UpdateProfile(updateProfile); if (stc == true) { Response.Redirect("~/Loggin.aspx"); } else { green0.Text = "Something went wrong!"; } }
public async Task<ActionResult> Login(UserLogin userLogin, string returnUrl) { if (ModelState.IsValid) { string result = await RegisterService.LoginAsync(userLogin, HttpContext.GetOwinContext().Authentication); if (!String.IsNullOrEmpty(result)) { ModelState.AddModelError("", result); } else { if (String.IsNullOrEmpty(returnUrl)) { return RedirectToAction("Index", "Home"); } return Redirect(returnUrl); } } return View(); }
protected void insertUser_Click(object sender, EventArgs e) { UserLogin usr = UserLogin_S.Loging(usrName.Text); if (usr != null) { if (usr.UserName == usrName.Text) { Label1.Text = "Not available!"; usrName.Focus(); } else { UserLogin newUser = new UserLogin(); newUser.UserName = usrName.Text; newUser.Password = pwd.Text; newUser.FullName = fullName.Text; UserLogin_S.InsertUser(newUser); green.Text = "Registered!"; Label1.Text = ""; } } else { UserLogin newUser = new UserLogin(); newUser.UserName = usrName.Text; newUser.Password = pwd.Text; newUser.FullName = fullName.Text; newUser.Mobile = mobi.Text; newUser.Apartment = addr.Text; bool status = UserLogin_S.InsertUser(newUser); if (status == true) { green.Text = "Registered!"; Label1.Text = ""; } } }
/// <summary> /// 确定登录 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonOk_Click(object sender, EventArgs e) { bool status = false; string userName = this._cbxUserName.Text; string password = this._txtPassword.Text; UserLogin[] ents = UserLogin.FindAll(); //数据库中无用户名及密码信息 if (ents == null) { LibCommon.Const.FIRST_TIME_LOGIN = true; status = false; Alert.alert(Const.ADD_USER_INFO, Const.LOGIN_FAILED_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); UserLogin ent = new UserLogin(); ent.LoginName = _cbxUserName.Text.ToString(); ent.PassWord = _txtPassword.Text; } else { //验证帐号密码是否正确 if (LoginSuccess(userName, password)) { status = true; } else { Alert.alert(Const.USER_NAME_OR_PWD_ERROR_MSG, Const.LOGIN_FAILED_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (status) { this.Hide(); _showForm.WindowState = FormWindowState.Maximized; _showForm.ShowDialog(); } }
private void btnLogin_Click(object sender, EventArgs e) { UserLogin login = new UserLogin(); login.UserValidate = new CKGLDAL(); //用户输入的过滤 var name = txtName.Text; var pwd = txtPwd.Text; User user = login.Login(name, pwd); if (user == null) { //用户登录失败 ShowPrompt("用户名或密码错误!"); } else { //用户登录成功 manageForm = new MangeForm(user,this); manageForm.Show(); this.Hide(); } }
public IActionResult Login(UserLogin userLogin) { return(View("Index", userLogin)); }
public void Add(UserLogin entity) { AddAsync(entity).Wait(); }
public AddCallLogViewModel(IMessenger messenger, UserLogin userLogin) : base(messenger, userLogin) { }
public ActionResult DriverDetail(DriverRegistrationViewModel model, string gender, string driverStatus) { if (Session["adminLog"] != null) { Driver driver = db.Drivers.SingleOrDefault(m => m.Id == model.Id); Vehicle vehicle = db.Vehicles.SingleOrDefault(m => m.DriverID == model.Id); PCOLicense pco = db.PCOLicenses.SingleOrDefault(m => m.DriverID == model.Id); UserLogin userLogin = db.UserLogins.SingleOrDefault(m => m.DriverID == model.Id); model.Status = driverStatus; if (ModelState.IsValid) { if (Convert.ToInt32(gender) == 1) { driver.Gender = "Male"; //model.Gender; } else { driver.Gender = "Female"; } { driver.Status = model.Status; driver.DriverId = model.DriverId; driver.DriverName = model.DriverName; driver.Address = model.Address; driver.DateOfBirth = model.DateOfBirth; driver.Nationality = model.Nationality; driver.City = model.City; driver.PostCode = model.PostCode; driver.DriverEmail = model.DriverEmail; driver.phNo = model.phNo; driver.Fax = model.Fax; driver.JoinDate = model.JoinDate; driver.LeftDate = model.LeftDate; driver.DirectCash = model.DirectCash; driver.LikeAccount = model.LikeAccount; //PCO Details pco.NiNumber = model.NiNumber; pco.DriverLicenseNo = model.DriverLicenseNo; pco.IssueDate = model.IssueDate; pco.ExpiryDate = model.ExpiryDate; pco.PcoDriverLicenseNo = model.PcoDriverLicenseNo; pco.PcoDriverLicenseIssueDate = model.PcoDriverLicenseIssueDate; pco.PcoDriverLicenseExpiryDate = model.PcoDriverLicenseExpiryDate; pco.selfEmployed = model.selfEmployed; //Vehicle Details vehicle.DriverID = model.Id; vehicle.CarType = model.CarType; vehicle.CarModel = model.CarModel; vehicle.Make = model.Make; vehicle.Year = model.Year; vehicle.Description = model.Description; vehicle.Registration = model.Registration; vehicle.Color = model.Color; vehicle.MaxPassenger = model.MaxPassenger; vehicle.MaxLuggage = model.MaxLuggage; vehicle.CarLicenseNo = model.CarLicenseNo; vehicle.VehicleLicenseExp = model.VehicleLicenseExp; vehicle.VehicleInsurance = model.VehicleInsurance; vehicle.InsuranceExpiry = model.InsuranceExpiry; vehicle.MotExpire = model.MotExpire; vehicle.RoadTaxExpiry = model.RoadTaxExpiry; //Login account Details userLogin.DriverID = model.Id; userLogin.UserFirstName = model.UserFirstName; userLogin.UserLastName = model.UserLastName; userLogin.UserEmail = model.UserEmail; userLogin.UserPhNo = model.UserPhNo; userLogin.Password = model.Password; } db.Entry(driver).State = EntityState.Modified; db.Entry(vehicle).State = EntityState.Modified; db.Entry(userLogin).State = EntityState.Modified; db.Entry(pco).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("driver", "admin")); } return(View(model)); } return(RedirectToAction("login")); }
public UserLogin AddLoginCredentials(UserLogin userLogin) { _dbContext.UserLogin.Add(userLogin); _dbContext.SaveChanges(); return(userLogin); }
public IActionResult UserLoginData([FromForm] UserLoginViewModel request) { #region Logged User Configuration UserLogin user = new UserLogin(); user.Identification = request.Identification; user.Password = request.Password; ServiceNode <UserLogin, LoginRespDTO> client = new ServiceNode <UserLogin, LoginRespDTO>(_localizer, _fc); ReturnMessage <LoginRespDTO> response = client.PostClient(request, "/api/v1/users/login"); if (response.IsCatched == 1) { ModelState.AddModelError("ServerResponse", response.Message); TempData["ServerResponseError"] = response.Message; return(RedirectToAction("Login")); } var UserData = response.Data.userData; if (request.RememberMe) { Response.Cookies.Append("UserKey", UserData.id.ToString(), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) }); Response.Cookies.Append("email", UserData.email.ToString(), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) }); Response.Cookies.Append("name", UserData.name, new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) }); Response.Cookies.Append("surname", UserData.surname, new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) }); Response.Cookies.Append("cId", UserData.countryId.ToString(), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) }); Response.Cookies.Append("rId", UserData.regionId.ToString(), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) }); Response.Cookies.Append("refreshToken", UserData.token, new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) }); Response.Cookies.Append("jwtToken", response.Data.jwtToken, new CookieOptions { Expires = DateTimeOffset.UtcNow.AddMinutes(1) }); HttpContext.Session.SetString("JwtSession", response.Data.jwtToken); } else { Response.Cookies.Append("UserKey", UserData.id.ToString()); Response.Cookies.Append("email", UserData.email.ToString()); Response.Cookies.Append("name", UserData.name); Response.Cookies.Append("surname", UserData.surname); Response.Cookies.Append("cId", UserData.countryId.ToString()); Response.Cookies.Append("rId", UserData.regionId.ToString()); Response.Cookies.Append("refreshToken", UserData.token, new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) }); Response.Cookies.Append("jwtToken", response.Data.jwtToken, new CookieOptions { Expires = DateTimeOffset.UtcNow.AddMinutes(1) }); HttpContext.Session.SetString("JwtSession", response.Data.jwtToken); } #endregion return(RedirectToAction("Index", "Home")); }
public ActionResult Login(UserLogin userLogin, string ReturnUrl = "") { string message = ""; var tourist = db.Tourists.Where(model => model.Email == userLogin.EmailID).FirstOrDefault(); var admin = db.Administrations.Where(model => model.AdminUsername == userLogin.EmailID).FirstOrDefault(); if (tourist != null) { if (string.Compare(Crypto.Hash(userLogin.Password), tourist.Password) == 0) { int timeout = userLogin.RememberMe ? 525600 : 20; var ticket = new FormsAuthenticationTicket(userLogin.EmailID, userLogin.RememberMe, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); Response.Cookies.Add(cookie); if (Url.IsLocalUrl(ReturnUrl)) { return(Redirect(ReturnUrl)); } else { return(RedirectToAction("Index", "AuthorizedTourist")); } } else { message = "Invalid Credentials provided"; } } else if (admin != null) { if (string.Compare(Crypto.Hash(userLogin.Password), admin.Password) == 0) { int timeout = userLogin.RememberMe ? 525600 : 20; var ticket = new FormsAuthenticationTicket(userLogin.EmailID, userLogin.RememberMe, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); Response.Cookies.Add(cookie); if (Url.IsLocalUrl(ReturnUrl)) { return(Redirect(ReturnUrl)); } else { return(RedirectToAction("Index", "AuthorizedAdmin")); } } else { message = "Invalid Credentials provided"; } } else { message = "Invalid Credentials provided"; } ViewBag.Message = message; return(View()); }
private UserLogin SetNewPassword( UserLogin user, string rawPassword ) { string hash = EncodeBcrypt( rawPassword ); if ( hash == null ) { throw new NotImplementedException( "Could not generate hash from password." ); } using ( var context = new RockContext() ) { var userService = new UserLoginService( context ); var contextUser = userService.Get( user.Id ); contextUser.Password = hash; context.SaveChanges(); return contextUser; } }
private bool AuthenticateSha1( UserLogin user, string password ) { try { if ( EncodeSha1( user.Guid, password, _encryptionKey ) == user.Password ) { SetNewPassword( user, password ); return true; } } catch { } foreach ( var encryptionKey in _oldEncryptionKeys ) { try { if ( EncodeSha1( user.Guid, password, encryptionKey ) == user.Password ) { SetNewPassword( user, password ); return true; } } catch { } } return false; }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var userLoginService = new UserLoginService(rockContext); var userLogin = userLoginService.Queryable().Where(a => a.ApiKey == tbKey.Text).FirstOrDefault(); if (userLogin != null && userLogin.PersonId != int.Parse(hfRestUserId.Value)) { // this key already exists in the database. Show the error and get out of here. nbWarningMessage.Text = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. "; nbWarningMessage.Visible = true; return; } rockContext.WrapTransaction(() => { var personService = new PersonService(rockContext); var changes = new List <string>(); var restUser = new Person(); if (int.Parse(hfRestUserId.Value) != 0) { restUser = personService.Get(int.Parse(hfRestUserId.Value)); } else { personService.Add(restUser); rockContext.SaveChanges(); restUser.Aliases.Add(new PersonAlias { AliasPersonId = restUser.Id, AliasPersonGuid = restUser.Guid }); } // the rest user name gets saved as the last name on a person History.EvaluateChange(changes, "Last Name", restUser.LastName, tbName.Text); restUser.LastName = tbName.Text; restUser.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid()).Id; if (cbActive.Checked) { restUser.RecordStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id; } else { restUser.RecordStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid()).Id; } if (restUser.IsValid) { if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), restUser.Id, changes); } } } // the description gets saved as a system note for the person var noteType = new NoteTypeService(rockContext) .Get(Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid()); var noteService = new NoteService(rockContext); var note = noteService.Get(noteType.Id, restUser.Id).FirstOrDefault(); if (note == null) { note = new Note(); noteService.Add(note); } note.NoteTypeId = noteType.Id; note.EntityId = restUser.Id; note.Text = tbDescription.Text; rockContext.SaveChanges(); // the key gets saved in the api key field of a user login (which you have to create if needed) var entityType = new EntityTypeService(rockContext) .Get("Rock.Security.Authentication.Database"); userLogin = userLoginService.GetByPersonId(restUser.Id).FirstOrDefault(); if (userLogin == null) { userLogin = new UserLogin(); userLoginService.Add(userLogin); } if (string.IsNullOrWhiteSpace(userLogin.UserName)) { userLogin.UserName = Guid.NewGuid().ToString(); } userLogin.IsConfirmed = true; userLogin.ApiKey = tbKey.Text; userLogin.PersonId = restUser.Id; userLogin.EntityTypeId = entityType.Id; rockContext.SaveChanges(); }); NavigateToParentPage(); }
public ActionResult Login() { UserLogin userLogin = new UserLogin(); return(View(userLogin)); }
public async Task <Security> GetLoginByCredentials(UserLogin login) { return(await _unitOfWork.SecurityRepository.GetLoginByCredentials(login)); }
public async Task <ServiceResponse <string> > Login(UserLogin request) { var result = await _http.PostAsJsonAsync("api/Auth/Login", request); return(await result.Content.ReadFromJsonAsync <ServiceResponse <string> >()); }
public ActionResult Login(RequestLoginInfo requestLoginInfo) { try { var resLogin = new ResponseLoginInfo(); resLogin = _authServices.LoginWithoutRefeshToken(requestLoginInfo); if (resLogin != null && resLogin.UserName != null) { var prevUserLogin = new UserLogin(); prevUserLogin = _userLoginServices.Get(requestLoginInfo.UserName); if (prevUserLogin == null || prevUserLogin.UserName == null) { var newUserLogin = new UserLogin { LoginId = "", UserName = requestLoginInfo.UserName, uuid = requestLoginInfo.uuid, ostype = requestLoginInfo.ostype, token = resLogin.token, registration_token = resLogin.registration_token }; var createdUser = _userLoginServices.Create(newUserLogin); if (createdUser != null) { return(Ok(new ResponseContext { code = (int)Common.ResponseCode.SUCCESS, message = Common.Message.LOGIN_SUCCESS, data = resLogin })); } else { return(StatusCode(StatusCodes.Status500InternalServerError, new ResponseMessage { status = "ERROR", message = "Cannot update user login information" })); } } else { var updateUserLogin = new UserLogin { LoginId = prevUserLogin.LoginId, UserName = requestLoginInfo.UserName, uuid = requestLoginInfo.uuid, ostype = requestLoginInfo.ostype, token = resLogin.token, registration_token = resLogin.registration_token }; var updateCount = _userLoginServices.Update(prevUserLogin.LoginId, updateUserLogin); if (updateCount >= 0) { return(Ok(new ResponseContext { code = (int)Common.ResponseCode.SUCCESS, message = Common.Message.LOGIN_SUCCESS, data = resLogin })); } else { return(StatusCode(StatusCodes.Status500InternalServerError, new ResponseMessage { status = "ERROR", message = "Cannot update user login information" })); } } } else { return(StatusCode(StatusCodes.Status401Unauthorized, new ResponseContext { code = (int)Common.ResponseCode.ERROR, message = Common.Message.INCORRECT_USERNAME_PASSWORD, data = null })); } } catch (System.Exception ex) { _logger.LogError(ex, ex.Message); return(StatusCode(StatusCodes.Status500InternalServerError, new ResponseMessage { status = "ERROR", message = ex.Message })); } }
public ActionResult LoginWithGoogle(string Email) { User_Role user = null; string[] temp = Email.Split('@'); string checkmail = temp[1]; string checkStudent; checkStudent = temp[0].Substring(temp[0].Length - 5); using (var ctx = new MSSEntities()) { user = ctx.User_Role .SqlQuery("Select * from User_Role where Login=@Login", new SqlParameter("@Login", Email)) .FirstOrDefault(); } if (user != null) { if (user.isActive == false) { ViewBag.Error = "Login Fail!"; return(View("Login")); } else { var RoleSession = new RoleLogin(); RoleSession.Role = user.Role_ID; var UserSession = new UserLogin(); UserSession.UserID = user.User_ID; UserSession.UserName = Email; Session.Add(CommonConstants.ROLE_Session, RoleSession); Session.Add(CommonConstants.User_Session, UserSession); return(RedirectToAction("Index", "Home")); } } if (user == null) { if (!checkmail.Equals("fpt.edu.vn")) { ViewBag.Error = "Login Fail!"; return(View("Login")); } else if (IsNumber(checkStudent)) { var RoleSession = new RoleLogin(); RoleSession.Role = 5; var UserSession = new UserLogin(); UserSession.UserID = 5; UserSession.UserName = Email; Session.Add(CommonConstants.ROLE_Session, RoleSession); Session.Add(CommonConstants.User_Session, UserSession); return(RedirectToAction("Index", "Home")); } else if (checkMentor(Email) == true) { var RoleSession = new RoleLogin(); RoleSession.Role = 3; var UserSession = new UserLogin(); UserSession.UserID = 3; UserSession.UserName = Email; Session.Add(CommonConstants.ROLE_Session, RoleSession); Session.Add(CommonConstants.User_Session, UserSession); return(RedirectToAction("Index", "Home")); } else { ViewBag.Error = "Login Fail!"; return(View("Login")); } } else { ViewBag.Error = "Login Fail!"; return(View("Login")); } }
public UserLogin AddVendorUserLogin(UserLogin userLogin) { _dbContext.UserLogin.Add(userLogin); _dbContext.SaveChanges(); return(userLogin); }
/// <summary> /// Creates or Finds a Person and UserLogin record, and returns the userLogin.UserName /// </summary> /// <param name="auth0UserInfo">The auth0 user information.</param> /// <returns></returns> public static string GetAuth0UserName(Auth0UserInfo auth0UserInfo) { string username = string.Empty; string userName = "******" + auth0UserInfo.sub; UserLogin user = null; using (var rockContext = new RockContext()) { // Query for an existing user var userLoginService = new UserLoginService(rockContext); user = userLoginService.GetByUserName(userName); // If no user was found, see if we can find a match in the person table if (user == null) { // Get name/email from auth0 userinfo string lastName = auth0UserInfo.family_name?.Trim()?.FixCase(); string firstName = auth0UserInfo.given_name?.Trim()?.FixCase(); string nickName = auth0UserInfo.nickname?.Trim()?.FixCase(); string email = auth0UserInfo.email; Person person = null; // If person had an email, get the first person with the same name and email address. if (!string.IsNullOrWhiteSpace(email)) { var personService = new PersonService(rockContext); person = personService.FindPerson(firstName, lastName, email, true); } var personRecordTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; var personStatusPending = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id; rockContext.WrapTransaction(() => { if (person == null) { person = new Person(); person.IsSystem = false; person.RecordTypeValueId = personRecordTypeId; person.RecordStatusValueId = personStatusPending; person.FirstName = firstName; person.LastName = lastName; person.Email = email; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; if (auth0UserInfo.gender == "male") { person.Gender = Gender.Male; } else if (auth0UserInfo.gender == "female") { person.Gender = Gender.Female; } else { person.Gender = Gender.Unknown; } if (person != null) { PersonService.SaveNewPerson(person, rockContext, null, false); } } if (person != null) { int typeId = EntityTypeCache.Get(typeof(Auth0Authentication)).Id; user = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "auth0", true); user.ForeignKey = auth0UserInfo.sub; } }); } if (user != null) { username = user.UserName; if (user.PersonId.HasValue) { var personService = new PersonService(rockContext); var person = personService.Get(user.PersonId.Value); if (person != null) { // If person does not have a photo, try to get the photo return with auth0 if (!person.PhotoId.HasValue && !string.IsNullOrWhiteSpace(auth0UserInfo.picture)) { // Download the photo from the url provided var restClient = new RestClient(auth0UserInfo.picture); var restRequest = new RestRequest(Method.GET); var restResponse = restClient.Execute(restRequest); if (restResponse.StatusCode == HttpStatusCode.OK) { var bytes = restResponse.RawBytes; // Create and save the image BinaryFileType fileType = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid()); if (fileType != null) { var binaryFileService = new BinaryFileService(rockContext); var binaryFile = new BinaryFile(); binaryFileService.Add(binaryFile); binaryFile.IsTemporary = false; binaryFile.BinaryFileType = fileType; binaryFile.MimeType = restResponse.ContentType; binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg"; binaryFile.FileSize = bytes.Length; binaryFile.ContentStream = new System.IO.MemoryStream(bytes); rockContext.SaveChanges(); person.PhotoId = binaryFile.Id; rockContext.SaveChanges(); } } } } } } return(username); } }
public ActionResult DriverDetail(int id) { if (Session["adminLog"] != null) { Driver driver = db.Drivers.SingleOrDefault(m => m.Id == id); Vehicle vehicle = db.Vehicles.SingleOrDefault(m => m.DriverID == id); PCOLicense pco = db.PCOLicenses.SingleOrDefault(m => m.DriverID == id); UserLogin userLogin = db.UserLogins.SingleOrDefault(m => m.DriverID == id); DriverRegistrationViewModel model = new DriverRegistrationViewModel(); model.DriverId = driver.DriverId; model.Id = driver.Id; model.DriverName = driver.DriverName; model.Address = driver.Address; model.DriverId = driver.DriverId; model.Status = driver.Status; model.Gender = driver.Gender; model.DateOfBirth = driver.DateOfBirth; model.Nationality = driver.Nationality; model.City = driver.City; model.PostCode = driver.PostCode; model.DriverEmail = driver.DriverEmail; model.phNo = driver.phNo; model.Fax = driver.Fax; model.JoinDate = driver.JoinDate; model.LeftDate = driver.LeftDate; model.DirectCash = driver.DirectCash; model.LikeAccount = driver.LikeAccount; //PCO Details model.NiNumber = pco.NiNumber; model.DriverLicenseNo = pco.DriverLicenseNo; model.IssueDate = pco.IssueDate; model.ExpiryDate = pco.ExpiryDate; model.PcoDriverLicenseNo = pco.PcoDriverLicenseNo; model.PcoDriverLicenseIssueDate = pco.PcoDriverLicenseIssueDate; model.PcoDriverLicenseExpiryDate = pco.PcoDriverLicenseExpiryDate; model.selfEmployed = pco.selfEmployed; //Vehicle Details model.CarType = vehicle.CarType; model.CarModel = vehicle.CarModel; model.Make = vehicle.Make; model.Year = vehicle.Year; model.Description = vehicle.Description; model.Registration = vehicle.Registration; model.Color = vehicle.Color; model.MaxPassenger = vehicle.MaxPassenger; model.MaxLuggage = vehicle.MaxLuggage; model.CarLicenseNo = vehicle.CarLicenseNo; model.VehicleLicenseExp = vehicle.VehicleLicenseExp; model.VehicleInsurance = vehicle.VehicleInsurance; model.InsuranceExpiry = vehicle.InsuranceExpiry; model.MotExpire = vehicle.MotExpire; model.RoadTaxExpiry = vehicle.RoadTaxExpiry; //Login account Details model.UserFirstName = userLogin.UserFirstName; model.UserLastName = userLogin.UserLastName; model.UserEmail = userLogin.UserEmail; model.UserPhNo = userLogin.UserPhNo; model.Password = userLogin.Password; model.ConformPassword = userLogin.Password; //==========Images========== model.DriverImage = driver.DriverImage; model.LicenseImage = pco.LicenseImage; model.CarImage = vehicle.CarImage; return(View(model)); } return(RedirectToAction("login")); }
/// <summary> /// Authenticates the user based on user name and password /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> public override bool Authenticate(UserLogin user, string password) { // don't implement throw new NotImplementedException(); }
private async Task <(bool, Security)> IsValidUser(UserLogin login) { var user = await _security.GetLoginByCredentials(login); return(user != null, user); }
/// <summary> /// Changes the password. /// </summary> /// <param name="user">The user.</param> /// <param name="oldPassword">The old password.</param> /// <param name="newPassword">The new password.</param> /// <param name="warningMessage">The warning message.</param> /// <returns></returns> public override bool ChangePassword(UserLogin user, string oldPassword, string newPassword, out string warningMessage) { warningMessage = "not supported"; return(false); }
public void Delete(UserLogin entity) { DeleteAsync(entity).Wait(); }
/// <summary> /// Sets the password. /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <exception cref="NotImplementedException"></exception> public override void SetPassword(UserLogin user, string password) { // don't implement throw new NotImplementedException(); }
public void Update(UserLogin entity) { UpdateAsync(entity).Wait(); }
public ActionResult LoginDashboard(UserLogin userLogin) { return(View()); }
public ActionResult LogIn(UserLogin login, string ReturnUrl = "") { try { if (Session["perdorues"] != null) { return(RedirectToAction("Index", "Kategoris")); } else { string message = ""; var v = db.Perdorues.Where(x => x.Email == login.Email).FirstOrDefault(); if (v != null) { if (string.Compare(Crypto.Hash(login.Fjalekalimi), v.Fjalekalimi) == 0) { int timeout = login.RememberMe ? 52600 : 1; var ticket = new FormsAuthenticationTicket(login.Email, login.RememberMe, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie); if (Url.IsLocalUrl(ReturnUrl)) { return(Redirect(ReturnUrl)); } else { int roli = Convert.ToInt32(db.Perdorues.Where(x => x.Email == login.Email).Select(x => x.ID_Roli).FirstOrDefault()); string statusi = db.Perdorues.Where(x => x.Email == login.Email).Select(x => x.Statusi).FirstOrDefault(); if (statusi == "Pasiv") { TempData["mssg"] = "<script>alert('Ju keni kaluar ne statusin pasiv nuk mund te logoheni');</script>"; return(RedirectToAction("Index", "Kategoris")); } else { if (roli == 1) { Session["perdorues"] = db.Perdorues.Where(x => x.Email == login.Email).Select(x => x.ID_Perdorues).FirstOrDefault(); return(RedirectToAction("Index", "Kategoris")); } //shkon tek faqja e administratorit else if (roli == 2) { Session["administrator"] = db.Perdorues.Where(x => x.Email == login.Email).Select(x => x.ID_Perdorues).FirstOrDefault(); return(RedirectToAction("Index", "Admin")); } if (roli == 3) { Session["menaxher"] = db.Perdorues.Where(x => x.Email == login.Email).Select(x => x.ID_Perdorues).FirstOrDefault(); return(RedirectToAction("Index", "Menaxher")); } } } } else { message = "invalid credentials"; } } else { message = "invalid credentials"; } ViewBag.Message = message; return(View(login)); } } catch (Exception ex) { logger.ErrorException("Error u gjend ne Kategori Controller, Login Action", ex); } return(View()); }
//[OutputCache(Duration = int.MaxValue, VaryByParam = "none")] public ActionResult RegUserDashboardIndex() { //model //Get User Id because this user was validated to exist on login // 'get person credetials to display on profile if (!TempData["LoginUname"].ToString().Equals(null) && !TempData["LoginUname"].ToString().Equals("DashLoad")) { //if refresh pass the id number of the person anmd thw data will passed into the database to request a refresh of the data model.NewPerson = UserLogin.GetPersonInfo(UserLogin.LoginGetUserID(TempData["LoginUname"].ToString(), TempData["LoginUpass"].ToString(), (bool)TempData["LoginUaccess"])); } else { model.NewPerson = UserLogin.GetPersonInfo(int.Parse(TempData["UserID"].ToString())); model.cattleInfo = CattleModel.GetCattleInfo(model.NewPerson.PId, model.NewPerson); // model.cattleInfo = CattleModel.GetCattleInfo(int.Parse(TempData["AidCurrent"].ToString())); model.CattleInfo = CattleModel.GetCattleIDs(model.NewPerson.PId); //sessions //login info TempData["LoginUname"] = "DashLoad"; TempData.Keep("LoginUname"); TempData["LoginUpass"] = model.NewPerson.PSurname; TempData.Keep("LoginUpass"); TempData["LoginUaccess"] = model.NewPerson.PId; TempData.Keep("LoginUaccess"); //animal info TempData["AidCurrent"] = model.cattleInfo.AId; TempData.Keep("AidCurrent"); //owner info TempData["Uname"] = model.NewPerson.PName; TempData.Keep("Uname"); TempData["USname"] = model.NewPerson.PSurname; TempData.Keep("USname"); TempData["UserID"] = model.NewPerson.PId; TempData.Keep("UserID"); return(View(model)); } //sessions TempData["LoginUname"] = "DashLoad"; TempData.Keep("LoginUname"); TempData["LoginUpass"] = model.NewPerson.PSurname; TempData.Keep("LoginUpass"); TempData["LoginUaccess"] = model.NewPerson.PId; TempData.Keep("LoginUaccess"); //owner info TempData["Uname"] = model.NewPerson.PName; TempData.Keep("Uname"); TempData["USname"] = model.NewPerson.PSurname; TempData.Keep("USname"); TempData["UserID"] = model.NewPerson.PId; TempData.Keep("UserID"); //get all available aniamls model.cattleInfo = CattleModel.GetCattleInfo(model.NewPerson.PId, model.NewPerson); model.CattleInfo = CattleModel.GetCattleIDs(model.NewPerson.PId); //animal id incase page is refreshed TempData["AidCurrent"] = model.cattleInfo.AId; TempData.Keep("AidCurrent"); return(View(model)); }
private void ControlVisible() { UserLogin uselogin = new UserLogin(); string message; string result = uselogin.GetRegister(AppData.OrgCode.Trim(), out message); if (result == "1") { foreach (Control ctrl in this.Controls) { if (ctrl is MenuStrip) { if (ctrl.Name == "MenuTop") { ctrl.Enabled = true; foreach (ToolStripMenuItem item in MenuTop.Items) { if (item.Name == "Seting") { item.Visible = true; foreach (ToolStripMenuItem dc in item.DropDownItems) { if (dc.Name == "Register") { dc.Visible = true; } else { dc.Visible = false; } } } else if (item.Name == "SysTSMI") { if (AppData.LoginName == "hrddiadmin") { item.Visible = true; } else { item.Visible = false; } } else { item.Visible = false; } } } else { ctrl.Enabled = false; } } else { ctrl.Visible = false; } } } else { foreach (Control ctrl in this.Controls) { if (ctrl is MenuStrip) { ctrl.Visible = true; foreach (ToolStripMenuItem item in MenuTop.Items) { if (item.Name == "SysTSMI") { if (AppData.LoginName == "hrddiadmin") { item.Visible = true; } else { item.Visible = false; } } else { item.Visible = true; } } } else { ctrl.Visible = true; } } } }
//Lấy theo id public UserLogin getByID(string id) { UserLogin User = shopModel.UserLogins.Find(id); return(User); }
private bool AuthenticateBcrypt( UserLogin user, string password ) { try { var hash = user.Password; var currentCost = hash.Substring( 4, 2 ).AsInteger(); var matches = BCrypt.Net.BCrypt.Verify( password, hash ); if ( matches && ( currentCost != ( GetAttributeValue( "BCryptCostFactor" ).AsIntegerOrNull() ?? 11 ) ) ) { SetNewPassword( user, password ); } return matches; } catch { return false; } }
public ActionResult Login(UserLogin userToLogin, string ReturnUrl = "") { //status will be checked within the form. //If it's false - the user'll see the according message string message = null; bool status = false; if (ModelState.IsValid) { using (RunetSoftDbEntities dataContext = new RunetSoftDbEntities()) { //verify if the user exists in the database var usr = dataContext.tblUsers.Where(u => u.UserName == userToLogin.UserName).FirstOrDefault(); if (usr != null) { //verify if the password matches if (Crypto.Verify(usr.Password, userToLogin.Password)) { //verify if the user account has been activated if ((usr.IsEmailVerified != null) && (Convert.ToBoolean(usr.IsEmailVerified))) { #region adding cookies to user's browser int timeout = userToLogin.IsRememberMeRequested ? 525600 : 20; // 525600 min = 1 year var ticket = new FormsAuthenticationTicket(userToLogin.UserName, userToLogin.IsRememberMeRequested, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie); #endregion #region redirection after the user has logged in if (Url.IsLocalUrl(ReturnUrl)) { return(Redirect(ReturnUrl)); } else { return(RedirectToAction("Index", "Home")); } #endregion } else { message = "Сначала необходимо активировать аккаунт, перейдя по ссылке, отправленной вам на e-mail"; } } else { message = "Логин или пароль неверный!"; } } else { message = "Пользователя с таким именем не существует!"; } } } ViewBag.Message = message; ViewBag.Status = status; return(View(userToLogin)); }
/// <summary> /// Encodes the password. /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <param name="encryptionKey">The encryption key.</param> /// <returns></returns> private string EncodePassword( UserLogin user, string password, byte[] encryptionKey ) { return EncodeBcrypt( password ); }
public ActionResult Login(LoginModel loginModel) { if (ModelState.IsValid) { var dao = new UserDAO(); var res = dao.Login(loginModel._Account.Email, Encryptor.MD5Hash(loginModel._Account.Password)); if (res == 1) { var user = dao.GetUserByEmail(loginModel._Account.Email); var userSession = new UserLogin(); userSession.Email = user.Email; userSession.UserID = user.UserID; Session.Add(CommonConstants.ADMIN_USER_SESSION, userSession); if (loginModel.RememberMe) { HttpCookie ckEmail = new HttpCookie("email"); ckEmail.Expires = DateTime.Now.AddDays(3600); ckEmail.Value = loginModel._Account.Email; Response.Cookies.Add(ckEmail); HttpCookie ckPassword = new HttpCookie("password"); ckPassword.Expires = DateTime.Now.AddDays(3600); ckPassword.Value = loginModel._Account.Password; Response.Cookies.Add(ckPassword); } return(RedirectToAction("Index", "Home")); } else if (res == 0) { ModelState.AddModelError("", "Tài khoản không tồn tại"); } else if (res == 2) { ModelState.AddModelError("", "Tài khoản của bạn đang bị khóa"); } else if (res == -1) { ModelState.AddModelError("", "Sai mật khẩu"); } else if (res == 3) { ModelState.AddModelError("", "Bạn không có quyền này"); } else if (res == -2) { return(RedirectToAction("Index", "Confirm")); } else { ModelState.AddModelError("", "Đăng nhập không thành công"); } } return(View("Index")); }
/// <summary> /// Sends the confirmation. /// </summary> /// <param name="userLogin">The user login.</param> private void SendConfirmation( UserLogin userLogin ) { string url = LinkedPageUrl( "ConfirmationPage" ); if ( string.IsNullOrWhiteSpace( url ) ) { url = ResolveRockUrl( "~/ConfirmAccount" ); } var mergeObjects = GlobalAttributesCache.GetMergeFields( CurrentPerson ); mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) ); var personDictionary = userLogin.Person.ToLiquid() as Dictionary<string, object>; mergeObjects.Add( "Person", personDictionary ); mergeObjects.Add( "User", userLogin ); var recipients = new List<RecipientData>(); recipients.Add( new RecipientData( userLogin.Person.Email, mergeObjects ) ); Email.Send( GetAttributeValue( "ConfirmAccountTemplate" ).AsGuid(), recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) ); }
public User Authenticate(UserLogin logInfo) { logInfo.Password = HashPassword(logInfo.Password); return(Authenticator.Authenticate(logInfo)); }